如何将.h文件中的常量导入python模块

Kon*_*tin 3 c python

建议的方法是将c-style(不是c ++,只是普通的旧c).h文件中定义的一堆常量导入到python模块中,以便可以在python的项目中使用它.在项目中我们使用混合语言,在perl中我可以通过使用h2xs实用程序来生成.pm模块.

常量定义看起来像

#define FOO 1
enum {
    BAR,
    BAZ
}; 
Run Code Online (Sandbox Code Playgroud)

等等

还提出了C风格的评论,必须妥善处理.

Mar*_*nen 5

我最近使用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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)