简体   繁体   English

我如何使用PYTHONPATH

[英]How do I use PYTHONPATH

I can't seem to get my module and class files to load from my script, but it loads fine from the REPL 我似乎无法从脚本中加载模块和类文件,但可以从REPL中很好地加载它

I have a fairly simply project structure 我有一个相当简单的项目结构

/home/user/project/
/home/user/project/bin/
/home/user/project/bin/myscript.py
/home/user/project/lib/
/home/user/project/lib/mymodule/__init__.py
/home/user/project/lib/mymodule/example.py

When I run the Python REPL, everything runs just fine. 当我运行Python REPL时,一切运行正常。

$export PYTHONPATH=./lib:$PYTHONPATH # Making sure that the REPL and script have access
$python
Python 2.7.8 blashblahblah
...
>from mymodule.example import MyClass
>test = MyClass()
>^D
$./bin/myscript.py
Traceback (most recent call last):
  File "myscript.py", line 5, in <module>
    from mymodule.example import MyClass
  File "/path/to/myscript.py", line 5, in <module>
    from mymodule.example import MyClass
ImportError: No module named example

I'm gonna answer my own question here. 我要在这里回答我自己的问题。 It turns out that the scripts name was 'mymodule.py' 原来,脚本名称为“ mymodule.py”

bin/
bin/mymodule.py
lib/
lib/mymodule/
lib/mymodule/__init__.py
lib/mymodule/example.py

When importing from the repl, the pythonpath resolves to the lib/mymodule module, and the code is loaded correctly (mostly). 从repl导入时,pythonpath解析为lib / mymodule模块,并且代码已正确(大部分)加载。 When running the script mymodule.py , the python interpreter prepends the script's directory bin/ to the pythonpath . 当运行脚本mymodule.py ,python解释器会将脚本的目录bin/附加到pythonpath The script then sees an import statement(s) for mymodule, and sources itself. 然后,脚本将看到mymodule的import语句,并自行获取资源。 When it fails to find a namespace that can be traversed to look for 'example' within the script, it throws the ImportError. 如果找不到可在脚本中遍历的名称空间以查找“ example”,则会引发ImportError。

The solution is to either rename the module or rename the script, (eg bin/my_module.py ) so that the namespaces don't collide. 解决方案是重命名模块或重命名脚本(例如bin/my_module.py ),以免名称空间冲突。

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

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