Python具有一种在启动时运行代码的机制。该网站的模块。
"This module is automatically imported during initialization."
站点模块将尝试导入
sitecustomize之前导入的命名模块
__main__。
usercustomize如果环境指示,它还将尝试导入名为的模块。
例如,您可以将sitecustomize.py文件放入包含以下内容的site-packages文件夹中:
import impimport osif 'MY_STARTUP_FILE' in os.environ: try: file_path = os.environ['MY_STARTUP_FILE'] folder, file_name = os.path.split(file_path) module_name, _ = os.path.splitext(file_name) fp, pathname, description = imp.find_module(module_name, [folder]) except Exception as e: # Broad exception handling since sitecustomize exceptions are ignored print "There was a problem finding startup file", file_path print repr(e) exit() try: imp.load_module(module_name, fp, pathname, description) except Exception as e: print "There was a problem loading startup file: ", file_path print repr(e) exit() finally: # "the caller is responsible for closing the file argument" from imp docs if fp: fp.close()
然后,您可以像这样运行脚本:
MY_STARTUP_FILE=/somewhere/bar.py python /somewhere_else/foo.py
- 您可以在foo.py之前运行任何脚本,而无需添加代码以重新导入
__main__
。 - 运行
export MY_STARTUP_FILE=/somewhere/bar.py
,无需每次都引用
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)