在python包中运行脚本

时间:2014-11-07 23:46:22

标签: python package

当模块不在Python路径中时,如何在模块中运行脚本?

考虑一些虚构的包:

package/
     __init__.py
    main.py
    helper/  
        __init__.py
        script.py
    other/  
        __init__.py
        anotherscript.py

假设我们想要运行script.py。当包在我的Python路径中时,这就完成了工作:

python -m package.helper.script

但如果情况并非如此呢?有没有办法告诉python模块的位置?像

这样的东西
python -m /path_to_my_package/package.helper.script

(显然,以上不起作用)

编辑:

(1)我正在寻找一种不涉及环境变量的解决方案。

(2)script.py包含相对导入,因此script.py的完整路径无法解决问题。

2 个答案:

答案 0 :(得分:0)

您的script.py应如下所示:

#!/usr/bin/python

#here your python code

if __name__ == "__main__":
    #run you helper

然后让您的脚本可执行:chmod +x script.py

从控制台运行./path_to_my_package/package/helper/script.py。

答案 1 :(得分:0)

你可以这样做。我假设这是来自cmd提示符或批处理文件?

SET PYTHONPATH=..\..\path\to\my\package;c:\other\path\thats\needed
python -m package.helper.script

您也可以将完整路径传递给您的python文件。但是,假设您的脚本不期望为其预先设置特定的环境路径。

python -m path_to_my_package/package/helper/script.py

编辑 - 如果您的script.py使用相对导入(并且您不想更改它),则除了将该根路径放入环境之外,无法执行此操作。如果需要,可以在脚本中执行此操作,而不是在cmd shell或批处理文件中设置它。但它需要在某个地方完成。以下是在脚本中设置环境路径的方法:

import sys
sys.path.append(r'..\..\path\to\my\package')
import package.other.anotherscript
相关问题