Вопрос

I am a python newbie. My objective is to convert a include file in C to python. For example.

input file (stdincl.c)

#define STDIN_BASEADDRESS 0x40600000
#define STDOUT_BASEADDRESS 0x40600000

/******************************************************************/

/* Definitions for driver UARTLITE */
#define XPAR_XUARTLITE_NUM_INSTANCES 1

expected output file (reg.py)

def STDIN_BASEADDRESS ():
    return 0x40600000
def STDOUT_BASEADDRESS ():
    return 0x40600000
# Definitions for driver UARTLITE 
def XPAR_XUARTLITE_NUM_INSTANCES ():
    return 1

I have tried to write codes using dictionary to hold a set of patterns to be replaced but it didnot really work. Any ideas is appreciated..

Это было полезно?

Решение

#define lines create constants. Just create variables in python for those:

STDIN_BASEADDRESS = 0x40600000
STDOUT_BASEADDRESS = 0x40600000

# ******************************************************************

# Definitions for driver UARTLITE
XPAR_XUARTLITE_NUM_INSTANCES = 1

So all you need to do is remove the #define part, and insert a = equals sign. A set of regular expressions would do the job:

import re
from functools import partial

replacements = (
    partial(re.compile(r'\s*#define ([A-Z_]+) (.*)').sub, r'\1 = \2'),
    partial(re.compile(r'\s*/\*\s*(.*?)\s*\*/').sub, r'# \1'),
)   

for line in inputsequence:
    for transform in replacements:
        line = transform(line)
    print line

Demo:

>>> import re
>>> from functools import partial
>>> replacements = (
...     partial(re.compile(r'\s*#define ([A-Z_]+) (.*)').sub, r'\1 = \2'),
...     partial(re.compile(r'\s*/\*\s*(.*?)\s*\*/').sub, r'# \1'),
... )   
>>> for line in inputsequence:
...     for transform in replacements:
...         line = transform(line)
...     print line
... 
STDIN_BASEADDRESS = 0x40600000
STDOUT_BASEADDRESS = 0x40600000

# ****************************************************************

# Definitions for driver UARTLITE
XPAR_XUARTLITE_NUM_INSTANCES = 1

If you still want to transform the defines to functions, just adjust the replacement pattern:

partial(re.compile(r'\s*#define ([A-Z_]+) (.*)').sub, r'def \1():\n    return \2'),

which results in:

def STDIN_BASEADDRESS():
    return 0x40600000
def STDOUT_BASEADDRESS():
    return 0x40600000

# ****************************************************************

# Definitions for driver UARTLITE
def XPAR_XUARTLITE_NUM_INSTANCES():
    return 1

Другие советы

You can use on linux and probably Mac OS X some other text processing tools

cat "<PATH TO YOUR FILE>" | awk '/^#define/ {printf("%s = %s",$2,$3)}' > "<PATH TO *.PY>"

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top