1

我是蟒蛇新手。我的目标是将 C 中的包含文件转换为 python。例如。

输入文件 (stdincl.c)

#define STDIN_BASEADDRESS 0x40600000
#define STDOUT_BASEADDRESS 0x40600000

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

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

预期的输出文件(reg.py)

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

我曾尝试使用字典编写代码来保存一组要替换的模式,但它并没有真正起作用。任何想法表示赞赏..

4

2 回答 2

1

#define行创建常量。只需在 python 中为这些创建变量:

STDIN_BASEADDRESS = 0x40600000
STDOUT_BASEADDRESS = 0x40600000

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

# Definitions for driver UARTLITE
XPAR_XUARTLITE_NUM_INSTANCES = 1

因此,您需要做的就是删除该#define部分,然后插入一个=等号。一组正则表达式可以完成这项工作:

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

演示:

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

如果您仍想将定义转换为函数,只需调整替换模式:

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

这导致:

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

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

# Definitions for driver UARTLITE
def XPAR_XUARTLITE_NUM_INSTANCES():
    return 1
于 2013-06-29T09:40:47.090 回答
1

您可以在 linux 和 Mac OS X 上使用其他一些文本处理工具

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

于 2013-06-29T10:30:46.283 回答