How to import constants from .h file into python module

What is the recommended way to import a bunch of constants defined in the c-style file (and not C ++, just the old c) .h into the python module so that it can be used in the python project part. In the project we use a combination of languages, and in perl I can do this import using the h2xs utility to create the .pm module.

The definition of constants looks like

#define FOO 1
enum {
    BAR,
    BAZ
}; 

and etc.

C style notes should also be properly handled.

+3
source share
4 answers

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

:

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
+5

- , - , . ... ,

#include "someotherfile.h"
enum NewEnum {
   A = -5,
   B = SOME_OTHER_ENUM, 
   C,
   D = 3
};

( ...)

, perl script, , .c, , , , . , (Java, ).

, , C .

+1

, : Python .h Python. .

0

script/, make python. #define , . python , , .

0

Source: https://habr.com/ru/post/1726272/


All Articles