Python 在同一文件夹中找不到模块

新手上路,请多包涵

我的 python 不知何故在同一目录中找不到任何模块。我究竟做错了什么? (python2.7)

所以我有一个目录’2014_07_13_test’,里面有两个文件:

  1. 测试.py
  2. 你好.py

哪里你好.py:

 # !/usr/local/bin/python
# -*- coding: utf-8 -*-

def hello1():
    print 'HelloWorld!'

和 test.py:

 # !/usr/local/bin/python
# -*- coding: utf-8 -*-

from hello import hello1

hello1()

仍然python给了我

>>> Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 4, in <module>
ImportError: No module named hello

怎么了?

原文由 Philipp_Kats 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 787
2 个回答

您的代码很好,我怀疑您的问题是您如何启动它。

您需要从“2014_07_13_test”目录启动 python。

打开命令提示符并“cd”进入“2014_07_13_test”目录。

例如:

 $ cd /path/to/2014_07_13_test
$ python test.py

如果你不能像这样’cd’进入目录,你可以将它添加到 sys.path

在 test.py 中:

 import sys, os
sys.path.append('/path/to/2014_07_13_test')

或设置/编辑 PYTHONPATH

一切都应该很好…

…好吧,您的“shebang”行(两个文件中的第一行)有一个小错误,“#”和“!”之间不应有空格

您应该使用 更好的shebang

此外,您不需要每个文件上的 shebang 行……只需要您打算从 shell 作为可执行文件运行的那些。

原文由 Jeremy Allen 发布,翻译遵循 CC BY-SA 3.0 许可协议

将 test.py 中的导入更改为:

 from .hello import hello1

原文由 jfn 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题