将 c 风格(不是 c++,只是普通的旧 c).h 文件中定义的一堆常量导入到 python 模块中的推荐方法是什么,以便它可以在项目的 python 部分中使用。在项目中,我们使用混合语言,在 Perl 中,我可以通过使用 h2xs 实用程序生成 .pm 模块来执行此导入。
常量定义看起来像
#define FOO 1
enum {
BAR,
BAZ
};
etc.
C 风格的注释也必须妥善处理。
我最近使用 pyparsing 库来扫描枚举常量。这是它,以及示例字符串和结果输出。请注意,它还处理注释和注释掉的部分。经过一点修改,它可以将常量填充到字典中。
from pyparsing import *
sample = '''
stuff before
enum hello {
Zero,
One,
Two,
Three,
Five=5,
Six,
Ten=10
}
in the middle
enum blah
{
alpha, // blah
beta, /* blah blah
gamma = 10 , */
zeta = 50
}
at the end
'''
# syntax we don't want to see in the final parse tree
_lcurl = Suppress('{')
_rcurl = Suppress('}')
_equal = Suppress('=')
_comma = Suppress(',')
_enum = Suppress('enum')
identifier = Word(alphas,alphanums+'_')
integer = Word(nums)
enumValue = Group(identifier('name') + Optional(_equal + integer('value')))
enumList = Group(enumValue + ZeroOrMore(_comma + enumValue))
enum = _enum + identifier('enum') + _lcurl + enumList('list') + _rcurl
enum.ignore(cppStyleComment)
for item,start,stop in enum.scanString(sample):
id = 0
for entry in item.list:
if entry.value != '':
id = int(entry.value)
print '%s_%s = %d' % (item.enum.upper(),entry.name.upper(),id)
id += 1
OUTPUT:
HELLO_ZERO = 0
HELLO_ONE = 1
HELLO_TWO = 2
HELLO_THREE = 3
HELLO_FIVE = 5
HELLO_SIX = 6
HELLO_TEN = 10
BLAH_ALPHA = 0
BLAH_BETA = 1
BLAH_ZETA = 50
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)