我有几个 python 脚本都以同一组行开头,我希望只能更改一次行。
例如这样的事情:
import pickle
import sys
sys.path.append("/Users/user/folder/")
import someOtherModules
x=someOtherModules.function()
我知道我可以将其保存为字符串,然后加载该字符串并运行 exec() 命令,但我想知道是否有更好的方法来执行此操作。
换句话说,我想导入模块列表并在每个脚本的开头运行一些函数。
最佳答案
您可以定义自己的模块。
# my_init.py
def init():
print("Initializing...")
只需在所有脚本的开头添加:
import my_init
my_init.init()
根据您的脚本和 my_init.py
所在的位置,您可能需要将它添加到您的 Python 用户站点目录,请参阅:Where should I put my own python module so that it can be imported
关于python - 始终在 python 脚本的开头导入相同的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48119332/