python - 有没有办法在 Python 中将代码转换为字符串,反之亦然?

标签 python macros

原来的问题是:

有没有办法像在 C 中声明的那样在 Python 中声明宏:

#define OBJWITHSIZE(_x) (sizeof _x)/(sizeof _x[0])

这是我想找出的:

有没有办法避免 Python 中的代码重复? 在我正在编写的程序的一部分中,我有一个函数:

def replaceProgramFilesPath(filenameBr):
  def getProgramFilesPath():
    import os
    return os.environ.get("PROGRAMFILES") + chr(92)
  return filenameBr.replace("<ProgramFilesPath>",getProgramFilesPath() )

在另一部分,我将这段代码嵌入到一个字符串中,稍后将被
输出到一个将自己运行的 python 文件:

"""
def replaceProgramFilesPath(filenameBr):
  def getProgramFilesPath():
    import os
    return os.environ.get("PROGRAMFILES") + chr(92)
  return filenameBr.replace("<ProgramFilesPath>",getProgramFilesPath() )
"""

我怎样才能构建一个“宏”来避免这种重复?

最佳答案

回答新问题。

在您的第一个 python 文件中(例如,称为 first.py):

import os

def replaceProgramFilesPath(filenameBr):
  new_path = os.environ.get("PROGRAMFILES") + chr(92)
  return filenameBr.replace("<ProgramFilesPath>", new_path)

在第二个 python 文件中(例如,称为 second.py):

from first import replaceProgramFilesPath
# now replaceProgramFilesPath can be used in this script.

请注意,first.py 需要位于 python 的模块搜索路径中或与 second.py 相同的目录中,以便您能够在second.py.

关于python - 有没有办法在 Python 中将代码转换为字符串,反之亦然?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2925174/

相关文章:

F# 类型提供程序与 Lisp 宏

c - 为什么我不能使用 #if 比较宏和枚举?

python - Tensorflow数据集如何获取数据生成器的形状?

python - Rest 框架序列化器总是为 is_valid 返回 False

python - 在自定义类中实现 __next__

c++ - 是否可以在 C++ 中使用宏交换两个变量的出现?

c++ - 一行调试宏

python - 考虑 `var = 5` ,一旦我将另一个值重新分配给 `5` ,计算机会自动删除值 `var` 吗?

python - 为什么这个使用 Python f-string 的打印语句输出双括号?

c - 当其他宏引发名称冲突时,如何使用其他宏定义宏