python中的宏(pep 638)

uxhixvfz  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(390)

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

(或者不管什么语法)。如果是的话,那怎么办呢?

14ifxucb

14ifxucb1#

这是一个非常非常基本的例子,用宏来替换基本的零参数文本。对于任何更为严肃/重要的事情,还有许多其他工具可以使用,例如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)

相关问题