在python包中运行脚本 [英] Run script within python package

查看:89
本文介绍了在python包中运行脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to run a script within the module when the module is not in my Python path?

考虑一些假想的软件包:

Consider some imaginary package:

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

说要运行script.py.当程序包在我的Python路径中时,就可以完成此工作:

Say wee want to run script.py. When the package is in my Python path, this does the job:

python -m package.helper.script

但是如果不是这种情况怎么办?有没有办法告诉python模块位置?像

But what if it's not the case? Is there a way to tell python the location of the module? Something like

python -m /path_to_my_package/package.helper.script

(显然,以上操作无效)

(clearly, the above doesn't work)

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

(1) I am looking for a solution that doesn't involve environmental variables.

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

(2) script.py contains relative import, so the full path to script.py does not solve the problem.

推荐答案

您可以执行此操作.我认为这是来自cmd提示符或批处理文件?

You could do this. I assume this is from a cmd prompt or batch file?

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

您还可以将完整路径传递给python文件.但这假设您的脚本不希望为其预先设置特定的环境路径.

You could also just pass the full path to your python file. But that assumes your script is not expecting a particular environment path to be pre-set for it.

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

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

EDIT - If your script.py uses relative imports (and you don't want to change that), then there is no way to do it except getting that root path into the environment. You can do this in your script if you want, instead of setting it in the cmd shell or batch file. But it needs to get done somewhere. Here's how you can set the environment path in your script:

import sys
sys.path.append(r'..\..\path\to\my\package')
import package.other.anotherscript

这篇关于在python包中运行脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆