简体   繁体   English

使用自定义sys.path调用python脚本

[英]call python script with custom sys.path

Sometimes I need to add custom paths to my python scripts to find certain modules, with sys.path.append("/some/directory/") at the beginning. 有时,我需要在python脚本中添加自定义路径以查找某些模块,并在开头添加sys.path.append("/some/directory/") However, I have a bunch of files that need to use this custom path and I'd like to avoid writing this in every file. 但是,我有一堆文件需要使用此自定义路径,因此我希望避免在每个文件中都编写此文件。 I have a main python script that automatically runs all these files using subprocess.call("python", "my_script.py") . 我有一个主要的python脚本,该脚本使用subprocess.call("python", "my_script.py")自动运行所有这些文件。 How could I achieve the equivalent of sys.path.append("/some/directory/") on every file, from the main script? 如何通过主脚本在每个文件上实现sys.path.append("/some/directory/")的等效功能?

If you add the directory to the environment variable PYTHONPATH before invoking subprocess.call() you can achieve the same result as adding the directory via sys.path.append() for a local call. 如果在调用subprocess.call()之前将目录添加到环境变量PYTHONPATH ,则可以获得与通过sys.path.append()为本地调用添加目录相同的结果。 Something like: 就像是:

import os
p = os.environ.get('PYTHONPATH', script_directory_to_add).split(os.pathsep)
if script_directory_to_add not in p:
    p.append(script_directory_to_add)
os.environ['PYTHONPATH'] = os.pathsep.join(p)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM