[英]Python3 - ImportError: No module named
I have 2 folders:我有 2 个文件夹:
my_python
code.py
MyCode
TestEntry.py
When I run the following commands:当我运行以下命令时:
cd /data/my_python
python3 code.py
The above works.以上工作。
However, if I in my home folder and then run this:但是,如果我在我的主文件夹中然后运行这个:
python3 /data/my_python/code.py
I get the following error:我收到以下错误:
Traceback (most recent call last):
File "/data/my_python/code.py", line 4, in <module>
from TestEntry import TestEntry
ImportError: No module named 'TestEntry'
Here is the code:这是代码:
import sys
import os
sys.path.append(os.path.abspath('../MyCode'))
from TestEntry import TestEntry
TestEntry().start(507,"My Param1","/param2",'.xyz',509)
Can you help me how to fix this?你能帮我解决这个问题吗?
That happens because, as @mkrieger1 mentioned, your sys.path
gets messed up.发生这种情况是因为,正如@mkrieger1 所提到的,您的
sys.path
搞砸了。 I have a previous answer here which explains how to set it.我在这里有一个先前的答案,它解释了如何设置它。 By
sys.path
getting messed up, I mean that python will look in the dir that you are running from, not the dir that the script you are running is in. Here is the recommended method: sys.path
搞砸了,我的意思是 python 将查看您正在运行的目录,而不是您正在运行的脚本所在的目录。这是推荐的方法:
import sys, os
sys.path.append(os.path.abspath(os.path.join('..', 'MyCode')))
... (your code)
or或者
import sys, os
sys.path.append(os.path.abspath(os.path.join(__file__, '..', 'MyCode')))
... (your code)
This way python will look in the dir of the file you are running as well.这样 python 也会在您正在运行的文件的目录中查找。
You are adding a relative path to sys
with your line sys.path.append(os.path.abspath('../MyCode'))
.您正在使用
sys.path.append(os.path.abspath('../MyCode'))
行添加到sys
的相对路径。 Instead, you need to import relative to that file you are calling.相反,您需要相对于您正在调用的文件进行导入。 Try this:
尝试这个:
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from TestEntry import TestEntry
TestEntry().start(507, "My Param1", "/param2", '.xyz', 509)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.