[英]Python import error from xx.xx import * : no module named
Here is my file structure: 这是我的文件结构:
-test
--m1
---t.py
--m2
---__init__.py
---utils.py
t.py: t.py:
from m2.utils import *
print foo()
utils.py: utils.py:
def foo():
return 5
__init__.py is empty __init__.py为空
It works in my local environment (macOS Sierra python 2.7.10): 它可以在我的本地环境中运行(macOS Sierra python 2.7.10):
Shangtong@Shangtong:~/GitHub/PaperReplication/test$ python m1/t.py
5
Shangtong@Shangtong:~/GitHub/PaperReplication/test$ echo $PYTHONPATH
:/Users/Shangtong/DevelopmentKits/libsvm-3.20/python
However it doesn't work in my server (Python 2.7.8): 但是,它在我的服务器中不起作用(Python 2.7.8):
[shangton@jasper test]$ python m1/t.py
Traceback (most recent call last):
File "m1/t.py", line 1, in <module>
from m2.utils import *
ImportError: No module named m2.utils
[shangton@jasper test]$ ls -al
total 16
drwxrwxr-x 4 shangton shangton 4096 Jan 28 09:10 .
drwx------ 4 shangton shangton 4096 Jan 28 10:09 ..
drwxrwxr-x 2 shangton shangton 4096 Jan 28 09:12 m1
drwxrwxr-x 2 shangton shangton 4096 Jan 28 10:09 m2
[shangton@jasper test]$ echo $PYTHONPATH
/global/software/python/Python-2.7.8/lib/python2.7/site-packages/:/global/software/python/Python-2.7.3/lib/python2.7/site-packages/:~/PaperReplication/:~/test/m2:~/test
You're demonstrating that your PYTHONPATH contains: 您正在证明您的PYTHONPATH包含:
~/test/m2:~/test
However, ~
is not actually a valid PATH component! 但是,
~
实际上不是有效的PATH组件! It's a hint to your shell to replace that character with your home directory (when unquoted, in the first position in a word, and otherwise where other conditions are met) -- but Python is not your shell, and if your shell didn't honor that hint when you were setting the environment variable (perhaps because, being in the middle of a string, it wasn't in leading position), it won't be honored later unless Python explicitly calls os.path.expanduser()
. 这是向您的shell提示用主目录替换该字符(不加引号时,在单词的第一个位置,否则满足其他条件)–但是Python不是您的shell,并且如果您的shell没有在设置环境变量时遵守该提示(可能是因为它位于字符串的中间,而不是处于领先地位),除非Python明确调用
os.path.expanduser()
否则以后将不接受该提示。
When setting an environment variable, use $HOME
: 设置环境变量时,请使用
$HOME
:
PYTHONPATH=$HOME/test
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.