Python无法在同一个文件夹中找到模块

2024-04-26 18:22:50 发布

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

我的python在同一个目录中找不到任何模块。 我做错什么了?(Python2.7)

所以我有一个目录“2014年7月13日测试”,里面有两个文件:

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

其中hello.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

怎么了?


Tags: 模块文件inpy目录hellobinusr
3条回答

我有一个类似的问题,我通过显式地将文件的目录添加到路径列表中来解决:

import os
import sys

file_dir = os.path.dirname(__file__)
sys.path.append(file_dir)

在那之后,我从同一个目录导入没有问题。

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

您需要从“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”行(两个文件中的第一行)有一个小错误,在“#”和“!”之间不应该有空格

有一个better shebang你应该使用。

你也不需要每个文件都有shebang行。。。只有那些你想作为可执行文件从shell运行的文件。

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

from .hello import hello1

相关问题 更多 >