繁体   English   中英

python (PEP 638) 中的宏

[英]Macros in python (PEP 638)

python 中一个较新的宏 PEP 是: https://www.python.org/dev/peps/pep-0638/ 使用它,是否可以定义如下宏:

PRINT = print ("Move from %s to %s." % (FROM, TO))

或者:

#define PRINT print ("Move from %s to %s." % (FROM, TO))

(或任何语法)。 如果是这样,那该怎么做?

这是一个使用宏进行基本零参数文本替换的非常非常基本的示例。 对于任何更严重/不平凡的事情,还有许多其他工具可以使用,例如C 的预处理器

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM