Python 仅当 运行 从包目录内导入时才有效

Python import only works when run from inside package directory

我有一个 python 脚本,它使用 gentle 来转录一些音频。

目前我必须将我的文件复制到 gentle repo 中,然后我可以 import gentle 并在稍后的代码中使用 gentle

但是我不想将我的文件复制到 gentle 目录中。我尝试将导入更改为 import gentle.gentle 但是无论哪种方式,当 运行 我的脚本来自父目录时,我都会收到以下错误:

Traceback (most recent call last):
  File "process_text.py", line 6, in <module>
    import gentle.gentle  # or just import gentle
  File "/usr/local/lib/python2.7/dist-packages/gentle/__init__.py", line 2, in <module>
    from resources import Resources
  File "/usr/local/lib/python2.7/dist-packages/gentle/resources.py", line 4, in <module>
    from util.paths import get_resource, ENV_VAR
ImportError: No module named util.paths

有没有一种无需将我的脚本复制到其目录中即可使用该模块的简便方法?谢谢!

这个问题有很多修复方法,有关详细信息,请参阅文档上的教程页面https://docs.python.org/3/tutorial/modules.html

基本上,如果 gentle 可以通过 pip 安装,您可能想尝试使用以下方法安装它:

pip install --user gentle

或者您可能想要使用 condavirtualenv 创建一个环境。 或者,您可以只设置 PYTHONPATH 环境变量以包含您需要的路径,例如

PYTHONPATH="/path/to/lib:$PYTHONPATH" python /path/to/script.py