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

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

我的python以某种方式无法在同一目录中找到任何模块。我究竟做错了什么?(python2.7)

所以我有一个目录“ 2014_07_13_test”,其中有两个文件:

  1. test.py
  2. 你好

在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

怎么了?

My python somehow can’t find any modules in the same directory. What am I doing wrong? (python2.7)

So I have one directory ‘2014_07_13_test’, with two files in it:

  1. test.py
  2. hello.py

where hello.py:

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

def hello1():
    print 'HelloWorld!'

and test.py:

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

from hello import hello1

hello1()

Still python gives me

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

What’s wrong?


回答 0

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

您需要从“ 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行,只需要将您打算从Shell中运行的文件作为可执行文件。

Your code is fine, I suspect your problem is how you are launching it.

You need to launch python from your ‘2014_07_13_test’ directory.

Open up a command prompt and ‘cd’ into your ‘2014_07_13_test’ directory.

For instance:

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

If you cannot ‘cd’ into the directory like this you can add it to sys.path

In test.py:

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

Or set/edit the PYTHONPATH

And all should be well…

…well there is a slight mistake with your ‘shebang’ lines (the first line in both your files), there shouldn’t be a space between the ‘#’ and the ‘!’

There is a better shebang you should use.

Also you don’t need the shebang line on every file… only the ones you intend to run from your shell as executable files.


回答 1

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

from .hello import hello1

Change your import in test.py to:

from .hello import hello1

回答 2

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

import os
import sys

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

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

I had a similar problem, I solved it by explicitly adding the file’s directory to the path list:

import os
import sys

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

After that, I had no problem importing from the same directory.


回答 3

这是我使用的通用解决方案。它解决了从同一文件夹中的模块导入的问题:

import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

将其放在模块顶部,该模块将显示错误“没有名为xxxx的模块”

Here is the generic solution I use. It solves the problem for importing from modules in the same folder:

import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

Put this at top of the module which gives the error “No module named xxxx”


回答 4

就我而言,Python无法找到它,因为我会将代码放在带有连字符的模块中,例如my-module。当我将其更改为my_module工作时。

In my case, Python was unable to find it because I’d put the code inside a module with hyphens, e.g. my-module. When I changed it to my_module it worked.


回答 5

我遇到了这个问题。我在同一目录中有三个文件夹,因此必须指定哪个文件夹。例如:从文件夹导入脚本

I ran into this issue. I had three folders in the same directory so I had to specify which folder. Ex: from Folder import script


回答 6

以下内容不能解决OP的问题,但标题和错误正是我所面对的。

如果项目中包含setup.py脚本,则可以使用python3 -m pip install -e .python3 setup.py install或来安装您所在的软件包python3 setup.py develop,并且该软件包将被安装,但仍可编辑(因此,在导入软件包时将看到代码更改)。如果没有setup.py,请理解

无论如何,OP面临的问题似乎不再存在了?

文件one.py

def function():
    print("output")

文件two.py

#!/usr/bin/env python3

import one
one.function()
chmod +x two.py # To allow execution of the python file
./two.py # Only works if you have a python shebang

Command line output: output

其他解决方案似乎“肮脏”

对于带有2个测试文件的OP,将它们修改为可以正常工作。但是,在其他实际情况下,可能不建议使用其他答案中列出的方法。它们要求您修改python代码或限制灵活性(从特定目录运行python文件),并且通常会带来麻烦。如果您刚刚克隆了一个项目,然后发生这种情况怎么办?它可能已经对其他人有用,并且无需更改代码。选择的答案还希望人们从特定文件夹运行脚本以使其起作用。这可能是长期烦恼的根源,这永远都不是一件好事。它还建议您将特定的python文件夹添加到PATH(可以通过python或命令行完成)。同样,如果您在几个月后重命名或移动文件夹会发生什么?您必须再次搜寻该页面,并最终发现您需要设置路径(几个月前您确实做了此设置),而您只需要更新路径(确保可以使用sys.path并以编程方式设置它即可,但这仍然很不稳定) )。许多令人烦恼的来源。

The following doesn’t solve the OP’s problem, but the title and error is exactly what I faced.

If your project has a setup.py script in it, you can install that package you are in, with python3 -m pip install -e . or python3 setup.py install or python3 setup.py develop, and this package will be installed, but still editable (so changes to the code will be seen when importing the package). If it doesn’t have a setup.py, make sense of it.

Anyway, the problem OP faces seems to not exist anymore?

file one.py:

def function():
    print("output")

file two.py:

#!/usr/bin/env python3

import one
one.function()
chmod +x two.py # To allow execution of the python file
./two.py # Only works if you have a python shebang

Command line output: output

Other solutions seem ‘dirty’

In the case of OP with 2 test files, modifying them to work is probably fine. However, in other real scenarios, the methods listed in the other answers is probably not recommended. They require you to modify the python code or restrict your flexibility (running the python file from a specific directory) and generally introduce annoyances. What if you’ve just cloned a project, and this happens? It probably already works for other people, and making code changes is unnecessary. The chosen answer also wants people to run a script from a specific folder to make it work. This can be a source of long term annoyance, which is never good. It also suggests adding your specific python folder to PATH (can be done through python or command line). Again, what happens if you rename or move the folder in a few months? You have to hunt down this page again, and eventually discover you need to set the path (and that you did exactly this a few months ago), and that you simply need to update a path (sure you could use sys.path and programmatically set it, but this can be flaky still). Many sources of great annoyance.