为什么我在执行死刑的时候会遇到麻烦系统路径追加在文件中而不是在Python控制台中?

2024-10-02 18:27:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试运行一个需要另一个目录中的包的脚本。在

这是有效的:

  • execfile("../test.py")在包父目录中启动python时
  • sys.path.append("package parent")在python解释器中调用{}

这不起作用(给出一个ImportError):

  • python ../test.py在包父目录中时
  • python test.py在脚本目录中时

test.py文件包含我在解释器中使用的相同的sys.path.append指令。在文件中运行还是在解释器中运行有区别?在


我的目录结构:

  • 在测试.py在
  • 包装
    • 在材料.py在

我得到的错误消息是:

from package.stuff import SomeClass
ImportError: No module named package.stuff


Tags: 文件pathpytest目录脚本packagesys
1条回答
网友
1楼 · 发布于 2024-10-02 18:27:16

交互式shell的行为与脚本行为不同的提示可以在^{docs中找到:

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

这应该可以解释为什么从交互式shell执行是有效的。但是,如果没有进一步的信息,只能猜测脚本失败的原因。在

设置PYTHONPATH与更新sys.path基本相同。在这个上{cd4}:

PYTHONPATH=/path/to/package1:/path/to/package2 python test.py

查看this postthe docs了解详细信息。在

相关问题 更多 >