# pypp.py
assert len(argv) == 3
# USAGE: $ python pypp.py script.py
# Does not allow arguments
# does not check whether it's in a string/comment.
# Very crude/basic, but but can be used for simple string-replacements
# such as the OP question.
from sys import argv
import re
with open(argv[-1], 'r') as f:
program = f.read()
matches = re.findall(r'\s*\#\s*define (\S+) (.+?)(?<!\\)\n', program)
for match in matches:
program = (program
.replace(match[0], '###', 1) # ignore first occurrence (macro itself)
.replace(match[0], match[1])
)
exec(program)
1条答案
按热度按时间14ifxucb1#
这是一个非常非常基本的例子,用宏来替换基本的零参数文本。对于任何更为严肃/重要的事情,还有许多其他工具可以使用,例如c的预处理器: