原来的问题是:
有没有办法像在 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/