标签归档:importerror

ImportError:没有名为bs4的模块(BeautifulSoup)

问题:ImportError:没有名为bs4的模块(BeautifulSoup)

我正在使用Python并使用Flask。当我在计算机上运行我的主Python文件时,它可以正常运行,但是当我激活venv并在终端中运行Flask Python文件时,它表示我的主Python文件具有“没有名为bs4的模块”。任何意见或建议,不胜感激。

I’m working in Python and using Flask. When I run my main Python file on my computer, it works perfectly, but when I activate venv and run the Flask Python file in the terminal, it says that my main Python file has “No Module Named bs4.” Any comments or advice is greatly appreciated.


回答 0

激活virtualenv,然后安装BeautifulSoup4:

$ pip install BeautifulSoup4

当您安装bs4使用easy_install,您在系统范围内进行了安装。因此,您的系统python可以导入它,但您的virtualenv python不能导入。如果您不需要bs4在系统python路径中安装,请卸载它并将其保留在virtualenv中。

有关virtualenvs的更多信息,请阅读此内容

Activate the virtualenv, and then install BeautifulSoup4:

$ pip install BeautifulSoup4

When you installed bs4 with easy_install, you installed it system-wide. So your system python can import it, but not your virtualenv python. If you do not need bs4 to be installed in your system python path, uninstall it and keep it in your virtualenv.

For more information about virtualenvs, read this


回答 1

对于python2.x

sudo pip install BeautifulSoup4

对于python3

sudo apt-get install python3-bs4

For python2.x:

sudo pip install BeautifulSoup4

For python3:

sudo apt-get install python3-bs4

回答 2

只需标记Balthazar的答案即可。跑步

pip install BeautifulSoup4

没有为我工作。改为使用

pip install beautifulsoup4

Just tagging onto Balthazar’s answer. Running

pip install BeautifulSoup4

did not work for me. Instead use

pip install beautifulsoup4

回答 3

pip3 install BeautifulSoup4

试试这个。这个对我有用。原因在这里得到了很好的解释..

pip3 install BeautifulSoup4

Try this. It works for me. The reason is well explained here..


回答 4

如果您将Anaconda用于软件包管理,则应执行以下操作:

conda install -c anaconda beautifulsoup4

If you are using Anaconda for package management, following should do:

conda install -c anaconda beautifulsoup4


回答 5

如果您使用Pycharm,请转到preferences - project interpreter - install bs4

如果尝试安装BeautifulSoup,它将仍然显示没有名为的模块bs4

If you use Pycharm, go to preferences - project interpreter - install bs4.

If you try to install BeautifulSoup, it will still show that no module named bs4.


回答 6

我建议您使用以下命令来卸载bs4库:

pip卸载bs4

然后使用以下命令进行安装:

须藤apt-get install python3-bs4

当我使用以下命令安装bs4库时,在Linux Ubuntu中遇到了相同的问题:

点安装bs4

I will advise you to uninstall the bs4 library by using this command:

pip uninstall bs4

and then install it using this command:

sudo apt-get install python3-bs4

I was facing the same problem in my Linux Ubuntu when I used the following command for installing bs4 library:

pip install bs4


回答 7

试试这个:

sudo python3 -m pip install bs4

Try this:

sudo python3 -m pip install bs4

回答 8

pip install --user BeautifulSoup4

pip install --user BeautifulSoup4


回答 9

pip3.7 install bs4

试试这个。它适用于python 3.7

pip3.7 install bs4

Try this. It works with python 3.7


回答 10

我做了@ rayid-ali所说的,除了我在Windows 10机器上,所以我省略了sudo。也就是说,我做了以下工作:

python3 -m pip install bs4

它就像一个pycharm。无论如何都像魅力一样工作。

I did what @rayid-ali said, except I’m on a Windows 10 machine so I left out the sudo. That is, I did the following:

python3 -m pip install bs4

and it worked like a pycharm. Worked like a charm anyway.


回答 11

最简单的是使用easy_install。

easy_install bs4 

如果pip失败,它将起作用。

The easiest is using easy_install.

easy_install bs4 

It will work if pip fails.


回答 12

很多针对Python 2编写的教程/参考资料都告诉您使用pip install somename。如果您使用的是Python 3,则要将其更改为pip3 install somename。

A lot of tutorials/references were written for Python 2 and tell you to use pip install somename. If you’re using Python 3 you want to change that to pip3 install somename.


回答 13

您可能想尝试使用安装bs4

pip install --ignore-installed BeautifulSoup4

如果上述方法不适合您。

You might want to try install bs4 with

pip install --ignore-installed BeautifulSoup4

if the methods above didn’t work for you.


回答 14

尝试重新安装模块,或者尝试使用以下命令与漂亮的汤一起安装

pip install --ignore-installed BeautifulSoup4

Try reinstalling the module OR Try installing with beautiful soup with the below command

pip install --ignore-installed BeautifulSoup4

回答 15

原始查询的附录:modules.py

help('modules')

$python modules.py

它列出了已经安装的模块bs4。

_codecs_kr          blinker             json                six
_codecs_tw          brotli              kaitaistruct        smtpd
_collections        bs4                 keyword             smtplib
_collections_abc    builtins            ldap3               sndhdr
_compat_pickle      bz2                 lib2to3             socket

正确的解决方案是:

pip install --upgrade bs4

应该解决问题。

不仅如此,其他模块也会显示相同的错误。因此,对于那些错误的模块,您必须以与上述相同的方式发出pip命令。

Addendum to the original query: modules.py

help('modules')

$python modules.py

It lists that module bs4 already been installed.

_codecs_kr          blinker             json                six
_codecs_tw          brotli              kaitaistruct        smtpd
_collections        bs4                 keyword             smtplib
_collections_abc    builtins            ldap3               sndhdr
_compat_pickle      bz2                 lib2to3             socket

Proper solution is:

pip install --upgrade bs4

Should solve the problem.

Not only that, it will show same error for other modules as well. So you got to issue the pip command same way as above for those errored module(s).


ImportError:libSM.so.6:无法打开共享库文件:没有这样的文件或目录

问题:ImportError:libSM.so.6:无法打开共享库文件:没有这样的文件或目录

尝试导入OpenCV时,使用import cv2我得到以下错误:

/usr/local/lib/python2.7/dist-packages/cv2/__init__.py in <module>()
      7 
      8 # make IDE's (PyCharm) autocompletion happy
----> 9 from .cv2 import *
     10 
     11 # wildcard import above does not import "private" variables like __version__

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

不确定如何解决-尝试使用Google的新协作工具。笔记本在这里:https : //drive.google.com/file/d/0B7-sJqBiyjCcRmFkMzl6cy1iN0k/view?usp=sharing

When trying to import OpenCV, using import cv2 I get the following error:

/usr/local/lib/python2.7/dist-packages/cv2/__init__.py in <module>()
      7 
      8 # make IDE's (PyCharm) autocompletion happy
----> 9 from .cv2 import *
     10 
     11 # wildcard import above does not import "private" variables like __version__

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

Not sure how to fix this – trying to play around with Google’s new Colaboratory tool. Notebook is here: https://drive.google.com/file/d/0B7-sJqBiyjCcRmFkMzl6cy1iN0k/view?usp=sharing


回答 0

通过将其作为脚本的前两行来解决此问题:

!pip install opencv-python
!apt update && apt install -y libsm6 libxext6
!apt-get install -y libxrender-dev

This fixed the problem by having it as the first two lines of the script:

!pip install opencv-python
!apt update && apt install -y libsm6 libxext6
!apt-get install -y libxrender-dev

回答 1

您需要添加sudo。我做了以下事情来安装它:

sudo apt-get install libsm6 libxrender1 libfontconfig1

然后这样做(可选!也许您将不需要它)

sudo python3 -m pip install opencv-contrib-python

终于完成了!

You need to add sudo . I did the following to get it installed :

sudo apt-get install libsm6 libxrender1 libfontconfig1

and then did that (optional! maybe you won’t need it)

sudo python3 -m pip install opencv-contrib-python

FINALLY got it done !


回答 2

对于CentOS,运行以下命令: sudo yum install libXext libSM libXrender

For CentOS, run this: sudo yum install libXext libSM libXrender


回答 3

现在有一个无头版本,opencv-python该版本删除了图形依赖性(如libSM)。您可以在发布页面上看到普通版/无头版(以及导致该问题GitHub问题);只需-headless在安装时添加,例如

pip install opencv-python-headless
# also contrib, if needed
pip install opencv-contrib-python-headless

There is now a headless version of opencv-python which removes the graphical dependencies (like libSM). You can see the normal / headless version on the releases page (and the GitHub issue leading to this); just add -headless when installing, e.g.,

pip install opencv-python-headless
# also contrib, if needed
pip install opencv-contrib-python-headless

回答 4

可能是您的问题 python-opencv版本。最好将您的版本降级到3.3.0.9,其中不包含任何GUI依赖项。在GitHub的此处找到了相同的问题的答案链接。

May be the problem is with your python-opencv version. It’s better to downgrade your version to 3.3.0.9 which does not include any GUI dependencies. Same question was found on GitHub here the link to the answer.


回答 5

我在python:3.7-slimdocker盒上遇到了openCV的类似问题。以下对我有用:

apt-get install build-essential libglib2.0-0 libsm6 libxext6 libxrender-dev

请查看是否有帮助!

I was facing similar issue with openCV on the python:3.7-slim docker box. Following did the trick for me :

apt-get install build-essential libglib2.0-0 libsm6 libxext6 libxrender-dev

Please see if this helps !


回答 6

我无法在Google Cloud Platform的Ubuntu上运行的Anaconda-Jupyter笔记本上安装cv2。但是我找到了一种方法,如下所示:

从ssh终端运行以下命令,并按照说明进行操作:

 sudo apt-get install libsm6 libxrender1 libfontconfig1

安装完毕后,打开Jupyter笔记本并运行以下命令:

!pip install opencv-contrib-python

注意:我尝试运行此命令:“ sudo python3 -m pip install opencv-contrib-python”,但显示错误。但是以上命令对我有用。

现在刷新笔记本页面,并通过import cv2在笔记本中运行检查它是否已安装。

I was not able to install cv2 on Anaconda-Jupyter notebook running on Ubuntu on Google Cloud Platform. But I found a way to do it as follows:

Run the following command from the ssh terminal and follow the instruction:

 sudo apt-get install libsm6 libxrender1 libfontconfig1

Once its installed Open the Jupyter notebook and run following command:

!pip install opencv-contrib-python

Note: I tried to run this command: “sudo python3 -m pip install opencv-contrib-python”but it was showing an error. But above command worked for me.

Now refresh the notebook page and check whether it’s installed or not by running import cv2 in the notebook.


回答 7

我遇到了同样的问题docker这些步骤对我有用:

apt update

然后:

apt install libsm6 libxext6 libxrender-dev

I had the same problem in docker and these steps worked for me:

apt update

then:

apt install libsm6 libxext6 libxrender-dev

ImportError:没有名为六个模块

问题:ImportError:没有名为六个模块

我正在尝试构建OpenERP项目,并完成了依赖项。现在出现此错误

Traceback (most recent call last):
  File "openerp-client.py", line 105, in <module>
  File "modules\__init__.pyo", line 23, in <module>
  File "modules\gui\__init__.pyo", line 22, in <module>
  File "modules\gui\main.pyo", line 33, in <module>
  File "rpc.pyo", line 29, in <module>
  File "common\__init__.pyo", line 22, in <module>
  File "common\common.pyo", line 26, in <module>
  File "tools\__init__.pyo", line 28, in <module>
  File "dateutil\relativedelta.pyo", line 12, in <module>
ImportError: No module named six

有人可以指导出什么问题以及如何解决吗???

I’m trying to build OpenERP project, done with dependencies. It’s giving this error now

Traceback (most recent call last):
  File "openerp-client.py", line 105, in <module>
  File "modules\__init__.pyo", line 23, in <module>
  File "modules\gui\__init__.pyo", line 22, in <module>
  File "modules\gui\main.pyo", line 33, in <module>
  File "rpc.pyo", line 29, in <module>
  File "common\__init__.pyo", line 22, in <module>
  File "common\common.pyo", line 26, in <module>
  File "tools\__init__.pyo", line 28, in <module>
  File "dateutil\relativedelta.pyo", line 12, in <module>
ImportError: No module named six

Could someone guide what’s wrong and how it can be fixed???


回答 0

您可能没有six安装Python模块。您可以在pypi上找到它。

要安装它:

$ easy_install six

(如果已pip安装,请pip install six改用)

You probably don’t have the six Python module installed. You can find it on pypi.

To install it:

$ easy_install six

(if you have pip installed, use pip install six instead)


回答 1

如果pip“说”了六个,但您仍然得到:

ImportError: No module named six.moves

尝试重新安装六个(为我工作):

pip uninstall six
pip install six

If pip “says” six is installed but you’re still getting:

ImportError: No module named six.moves

try re-installing six (worked for me):

pip uninstall six
pip install six

回答 2

在Ubuntu和Debian上

apt-get install python-six

绝招。

使用sudo apt-get install python-six,如果你得到一个错误说“权限被拒绝”。

On Ubuntu and Debian

apt-get install python-six

does the trick.

Use sudo apt-get install python-six if you get an error saying “permission denied”.


回答 3

对于Mac OS X:

pip install --ignore-installed six

For Mac OS X:

pip install --ignore-installed six

回答 4

我做了以下工作来解决上述问题。我尝试运行内置的exe时遇到了上述问题,即使我使用pyinstaller成功构建了exe。我是在Windows 10上完成的。

  1. 转到https://pypi.org/project/six/#files
  2. 下载“ six-1.14.0.tar.gz(33.9 kB)”
  3. 解压缩它,将“ six.py”复制并粘贴到您的源目录中。
  4. 将“六个”模块导入您的源代码(导入六个)
  5. 运行源脚本。

I did the following to solve the mentioned problem. I got the mentioned problem when I was trying to run the built exe, even I successfully built the exe using pyinstaller. I did this on Windows 10.

  1. go to https://pypi.org/project/six/#files
  2. download “six-1.14.0.tar.gz (33.9 kB)”
  3. unzip it, copy and paste “six.py” into your source directory.
  4. import “six” module into your source code (import six)
  5. run source script.

回答 5

pip install --ignore-installed six

资料来源:1233个竖起大拇指在此评论

pip install --ignore-installed six

Source: 1233 thumbs up on this comment


回答 6

在Ubuntu Bionic(18.04)上,已经为python2和python3安装了六个,但是启动Wammu时出现错误。@ 3ygun解决方案为我解决了

ImportError: No module named six

启动Wammu时

如果发生在python3程序中,则附带六个

pip3 install six

如果没有pip3:

apt install python3-pip

在Ubuntu下使用sudo

on Ubuntu Bionic (18.04), six is already install for python2 and python3 but I have the error launching Wammu. @3ygun solution worked for me to solve

ImportError: No module named six

when launching Wammu

If it’s occurred for python3 program, six come with

pip3 install six

and if you don’t have pip3:

apt install python3-pip

with sudo under Ubuntu!


ImportError:在Windows 7 32位中运行pip –version命令时无法导入名称main

问题:ImportError:在Windows 7 32位中运行pip –version命令时无法导入名称main

我已经为32位Windows安装了与pip和setuptools捆绑在一起的最新python(2.7.9)。我尝试重新安装pip,但问题仍然存在。

这是pip --version在Administrator cmd中运行后的错误:

Traceback (most recent call last):
 File "D:\Python\lib\runpy.py", line 162, in _run_module_as_main
  "__main__", fname, loader, pkg_name)
 File "D:\Python\lib\runpy.py", line 72, in _run_code 
  exec code in run_globals
 File "D:\Python\Scripts\pip.exe\__main__.py", line 5, in <module>
ImportError: cannot import name main

I’ve installed the latest python (2.7.9) bundled with pip and setuptools for windows 32-bit. I’ve tried reinstalling pip but the problem persists.

Here’s the error after running pip --version in Administrator cmd:

Traceback (most recent call last):
 File "D:\Python\lib\runpy.py", line 162, in _run_module_as_main
  "__main__", fname, loader, pkg_name)
 File "D:\Python\lib\runpy.py", line 72, in _run_code 
  exec code in run_globals
 File "D:\Python\Scripts\pip.exe\__main__.py", line 5, in <module>
ImportError: cannot import name main

回答 0

尽管最初的问题似乎来自2015年,但这个“错误”似乎也影响了用户的安装pip-10.0.0

解决方法是不修改pip,而是更改pip的调用方式。而不是通过Python本身调用/usr/bin/pipcall pip。例如,代替以下内容:

pip install <package>

如果来自Python版本2(或称为默认Python二进制文件python),请执行以下操作:

python -m pip install <package>

还是从Python版本3:

python3 -m pip install <package> 

Even though the original question seems to be from 2015, this ‘bug’ seems to affect users installing pip-10.0.0 as well.

The workaround is not to modify pip, however to change the way pip is called. Instead of calling /usr/bin/pip call pip via Python itself. For example, instead of the below:

pip install <package>

If from Python version 2 (or default Python binary is called python) do :

python -m pip install <package>

or if from Python version 3:

python3 -m pip install <package> 

回答 1

该错误位于pip 10.0.0中。

在Linux中,您需要从以下位置修改文件:/ usr / bin / pip:

from pip import main
if __name__ == '__main__':
    sys.exit(main())

对此:

from pip import __main__
if __name__ == '__main__':
    sys.exit(__main__._main())

The bug is found in pip 10.0.0.

In linux you need to modify file: /usr/bin/pip from:

from pip import main
if __name__ == '__main__':
    sys.exit(main())

to this:

from pip import __main__
if __name__ == '__main__':
    sys.exit(__main__._main())

回答 2

在Ubuntu Server 16上,python27也有相同的问题。试试这个:

更改

from pip import main
if __name__ == '__main__':
    sys.exit(main())

from pip._internal import main
if __name__ == '__main__':
    sys.exit(main())

On Ubuntu Server 16, I have the same problem with python27. Try this:

Change

from pip import main
if __name__ == '__main__':
    sys.exit(main())

To

from pip._internal import main
if __name__ == '__main__':
    sys.exit(main())

回答 3

在Windows 10上,我使用以下命令降级了pip:

python -m pip uninstall pip
python -m pip install pip==9.0.3

这也应该在Linux和Mac上也可以使用。

On Windows 10, I used the following commands to downgrade pip:

python -m pip uninstall pip
python -m pip install pip==9.0.3

This should also work on Linux and Mac too.


回答 4

我遇到了同样的问题,但是使用apt和pip卸载并重新安装对我来说不起作用。

我看到了另一个解决方案,它提供了一种恢复pip3路径的简便方法:

sudo python3 -m pip uninstall pip && sudo apt install python3-pip --reinstall

I had the same problem, but uninstall and reinstall with apt and pip didn’t work for me.

I saw another solution that presents a easy way to recover pip3 path:

sudo python3 -m pip uninstall pip && sudo apt install python3-pip --reinstall

回答 5

我通过使用重新安装pip来解决此问题get-pip.py

  1. 从官方链接下载get-pip:https//pip.pypa.io/en/stable/installing/#upgrading-pip
  2. 使用commande:运行它python get-pip.py

点子是固定的,可以完美地工作。

i fixed the problem by reinstalling pip using get-pip.py.

  1. Download get-pip from official link: https://pip.pypa.io/en/stable/installing/#upgrading-pip
  2. run it using commande: python get-pip.py.

And pip is fixed and work perfectly.


回答 6

在MacOS上,如果您通过Homebrew安装了python,请在 /usr/local/opt/python/libexec/bin/pip

from pip.internal import main

from pip._internal import main

或使用这种衬板: sed -i '' "s/from pip import main/from pip._internal import main/" /usr/local/opt/python/libexec/bin/pip

说明:

此问题是由于pip版本10中的内部移动命名空间的更改main._internal以及Homebrew仍然从旧位置(以前是版本9中)查找的bin脚本引起的。问题和一些讨论https://github.com/pypa/pip/issues/5240

On MacOS if you’ve installed python via Homebrew, change the line in /usr/local/opt/python/libexec/bin/pip

from

from pip.internal import main

to

from pip._internal import main

Or use this one liner: sed -i '' "s/from pip import main/from pip._internal import main/" /usr/local/opt/python/libexec/bin/pip

Explanation:

The issue is caused by the changes in pip version 10 moving internal namespace under main._internal and the bin script put in place by homebrew still looking it from the old place (where it used to be in version 9). Issue and some discussion https://github.com/pypa/pip/issues/5240


回答 7

如果您有要插入的硬链接PATH(即,如果安装了多个python版本),然后升级了pip,则也可能会遇到此错误。

解决方案包括再次创建硬链接。甚至更好的是,停止使用硬链接并使用软链接。

If you have a hardlink to pip in your PATH (i.e. if you have multiple python versions installed) and then you upgrade pip, you may also encounter this error.

The solution consists in creating the hardlink again. Or even better, stop using hardlinks and use softlinks.


回答 8

在Windows 10上,我遇到了同样的问题。PIP 19已安装在我的系统中,但没有显示。错误是No Module Found

python -m pip uninstall pip
python -m pip install pip==9.0.3

降级pip到9.0.3对我来说很好。

On Windows 10, I had the same problem. PIP 19 was already installed in my system but wasn’t showing up. The error was No Module Found.

python -m pip uninstall pip
python -m pip install pip==9.0.3

Downgrading pip to 9.0.3 worked fine for me.


回答 9

对于使用pip 10和PyCharm遇到类似问题的人,请在此处下载最新版本

For those having similar trouble using pip 10 with PyCharm, download the latest version here


回答 10

它适用于Ubuntu 16.04。第1步:

 sudo gedit /home/user_name/.local/bin/pip

将打开一个包含以下内容的文件:

#!/usr/bin/python

# -*- coding: utf-8 -*-
import re
import sys

from pip import main

if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
    sys.exit(main())

将更main改为__main__,如下所示:

#!/usr/bin/python

# -*- coding: utf-8 -*-
import re
import sys

from pip import __main__

if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
    sys.exit(__main__._main())

保存文件并关闭它。您完成了!

It works on ubuntu 16.04. Step 1:

 sudo gedit /home/user_name/.local/bin/pip

a file opens with the content:

#!/usr/bin/python

# -*- coding: utf-8 -*-
import re
import sys

from pip import main

if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
    sys.exit(main())

Change the main to __main__ as it appears below:

#!/usr/bin/python

# -*- coding: utf-8 -*-
import re
import sys

from pip import __main__

if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
    sys.exit(__main__._main())

Save the file and close it. And you are done!


回答 11

试试这个

#!/usr/bin/python
# GENERATED BY DEBIAN

import sys

# Run the main entry point, similarly to how setuptools does it, but because
# we didn't install the actual entry point from setup.py, don't use the
# pkg_resources API.i
try:
    from pip import main
except ImportError:
    from pip._internal import main
if __name__ == '__main__':
    sys.exit(main())

try this

#!/usr/bin/python
# GENERATED BY DEBIAN

import sys

# Run the main entry point, similarly to how setuptools does it, but because
# we didn't install the actual entry point from setup.py, don't use the
# pkg_resources API.i
try:
    from pip import main
except ImportError:
    from pip._internal import main
if __name__ == '__main__':
    sys.exit(main())

回答 12

一个适用于Ubuntu的简单解决方案,但也可以在Windows上解决该问题:

刚打电话

pip install --upgrade pip

A simple solution that works with Ubuntu, but may fix the problem on windows too:

Just call

pip install --upgrade pip

回答 13

这在尝试使用python3.6时解决了我在ubuntu 18.04中的问题:

rm -rf ~/.local/lib/python3.6

您可以使用mv将文件夹移动到另一个位置,而不是将其删除,以进行测试:

mv ~/.local/lib/python3.6 ./python3.6_old

This solved my problem in ubuntu 18.04 when trying to use python3.6:

rm -rf ~/.local/lib/python3.6

You can move the folder to another place using mv instead of deleting it too, for testing:

mv ~/.local/lib/python3.6 ./python3.6_old

回答 14

打开您的终端Linux。

hash -d pip

Open your terminal linux.

hash -d pip

回答 15

在我们的案例中,在2020年使用Python3,解决此问题的方法是将Python安装移至cloud-init实例化VM 的启动脚本。

当我们尝试使用VM生命周期中稍后由用户调用的脚本来安装Python时,我们也遇到了相同的错误,但是将相同的Python安装代码移至该cloud-init脚本可以解决此问题。

In our case, in 2020 using Python3, the solution to this problem was to move the Python installation to the cloud-init startup script which instantiated the VM.

We had been encountering this same error when we had been trying to install Python using scripts that were called by users later in the VM’s life cycle, but moving the same Python installation code to the cloud-init script eliminated this problem.


尝试运行Python脚本时出现“ ImportError:未命名模块”

问题:尝试运行Python脚本时出现“ ImportError:未命名模块”

我正在尝试运行一个脚本,该脚本除其他外将启动python脚本。我收到一个ImportError:没有名为…的模块,但是,如果我启动ipython并通过解释器以相同的方式导入相同的模块,则该模块将被接受。

怎么回事,我该如何解决?我试图了解python如何使用PYTHONPATH,但是我感到非常困惑。任何帮助将不胜感激。

I’m trying to run a script that launches, amongst other things, a python script. I get a ImportError: No module named …, however, if I launch ipython and import the same module in the same way through the interpreter, the module is accepted.

What’s going on, and how can I fix it? I’ve tried to understand how python uses PYTHONPATH but I’m thoroughly confused. Any help would greatly appreciated.


回答 0

由于命令行IPython解释器使用当前路径的方式与单独进程(例如IPython笔记本,外部进程等)的方式不同,因此会出现此问题。IPython将寻找要导入的模块,这些模块不仅可以在sys.path中找到,而且可以在当前工作目录中找到。从命令行启动解释器时,您正在操作的当前目录与在ipython中启动的目录相同。如果运行

import os
os.getcwd() 

您会看到这是真的。

但是,假设您使用的是ipython笔记本,请运行,os.getcwd()而当前的工作目录是您告诉笔记本在ipython_notebook_config.py文件中操作笔记本的文件夹(通常使用该c.NotebookManager.notebook_dir设置)。

解决方案是为python解释器提供您的模块路径。最简单的解决方案是将该路径附加到sys.path列表中。在您的笔记本中,首先尝试:

import sys
sys.path.append('my/path/to/module/folder')

import module-of-interest

如果这不起作用,则您手上的问题与导入路径无关,您应提供有关问题的更多信息。

解决此问题的更好(且更永久)的方法是设置PYTHONPATH,它为解释器提供了用于python包/模块的其他目录。将PYTHONPATH编辑或设置为全局变量是os依赖的,这里将在UnixWindows上进行详细讨论。

This issue arises due to the ways in which the command line IPython interpreter uses your current path vs. the way a separate process does (be it an IPython notebook, external process, etc). IPython will look for modules to import that are not only found in your sys.path, but also on your current working directory. When starting an interpreter from the command line, the current directory you’re operating in is the same one you started ipython in. If you run

import os
os.getcwd() 

you’ll see this is true.

However, let’s say you’re using an ipython notebook, run os.getcwd() and your current working directory is instead the folder in which you told the notebook to operate from in your ipython_notebook_config.py file (typically using the c.NotebookManager.notebook_dir setting).

The solution is to provide the python interpreter with the path-to-your-module. The simplest solution is to append that path to your sys.path list. In your notebook, first try:

import sys
sys.path.append('my/path/to/module/folder')

import module-of-interest

If that doesn’t work, you’ve got a different problem on your hands unrelated to path-to-import and you should provide more info about your problem.

The better (and more permanent) way to solve this is to set your PYTHONPATH, which provides the interpreter with additional directories look in for python packages/modules. Editing or setting the PYTHONPATH as a global var is os dependent, and is discussed in detail here for Unix or Windows.


回答 1

__init__.py运行python项目时,只需在显示错误的文件夹下创建一个名称为空的python文件即可。

Just create an empty python file with the name __init__.py under the folder which showing error, while you running the python project.


回答 2

确保它们都使用相同的解释器。这在Ubuntu上发生在我身上:

$ ipython3 -c 'import sys; print(sys.version)'
3.4.2 (default, Jun 19 2015, 11:34:49) \n[GCC 4.9.1]

$ python3 -c 'import sys; print(sys.version)'
3.3.0 (default, Nov 27 2012, 12:11:06) \n[GCC 4.6.3]

而且sys.path是两个解释不同。为了解决这个问题,我删除了Python 3.3。

Make sure they are both using the same interpreter. This happened to me on Ubuntu:

$ ipython3 -c 'import sys; print(sys.version)'
3.4.2 (default, Jun 19 2015, 11:34:49) \n[GCC 4.9.1]

$ python3 -c 'import sys; print(sys.version)'
3.3.0 (default, Nov 27 2012, 12:11:06) \n[GCC 4.6.3]

And sys.path was different between the two interpreters. To fix it, I removed Python 3.3.


回答 3

主要原因是Python和IPython的sys.paths不同。

请参考lucypark链接,该解决方案适用于我的情况。它通过安装opencv时发生

conda install opencv

在iPython中出现导入错误,有三个步骤可以解决此问题:

import cv2
ImportError: ...

1.使用以下命令检查Python和iPython中的路径

import sys
sys.path

您会发现与Python和Jupyter不同的结果。第二步,只需使用sys.path.append 尝试错误即可修复错过的路径。

2.临时解决方案

在iPython中:

import sys
sys.path.append('/home/osboxes/miniconda2/lib/python2.7/site-packages')
import cv2

ImportError:..问题的解决

3.永久解决方案

创建一个iPython配置文件并设置初始追加:

在bash shell中:

ipython profile create
... CHECK the path prompted , and edit the prompted config file like my case
vi /home/osboxes/.ipython/profile_default/ipython_kernel_config.py

在vi中,附加到文件:

c.InteractiveShellApp.exec_lines = [
 'import sys; sys.path.append("/home/osboxes/miniconda2/lib/python2.7/site-packages")'
]

完成

The main reason is the sys.paths of Python and IPython are different.

Please refer to lucypark link, the solution works in my case. It happen when install opencv by

conda install opencv

And got import error in iPython, There are three steps to solve this issue:

import cv2
ImportError: ...

1. Check path in Python and iPython with following command

import sys
sys.path

You will find different result from Python and Jupyter. Second step, just use sys.path.append to fix the missed path by try-and-error.

2. Temporary solution

In iPython:

import sys
sys.path.append('/home/osboxes/miniconda2/lib/python2.7/site-packages')
import cv2

the ImportError:.. issue solved

3. Permanent solution

Create an iPython profile and set initial append:

In bash shell:

ipython profile create
... CHECK the path prompted , and edit the prompted config file like my case
vi /home/osboxes/.ipython/profile_default/ipython_kernel_config.py

In vi, append to the file:

c.InteractiveShellApp.exec_lines = [
 'import sys; sys.path.append("/home/osboxes/miniconda2/lib/python2.7/site-packages")'
]

DONE


回答 4

这样做是sys.path.append('my-path-to-module-folder')可行的,但是为了避免每次要使用IMod时都必须在IPython中执行此操作,可以将其添加export PYTHONPATH="my-path-to-module-folder:$PYTHONPATH"~/.bash_profile文件中。

Doing sys.path.append('my-path-to-module-folder') will work, but to avoid having to do this in IPython every time you want to use the module, you can add export PYTHONPATH="my-path-to-module-folder:$PYTHONPATH" to your ~/.bash_profile file.


回答 5

在安装ipython之前,我通过easy_install安装了模块;说sudo easy_install mechanize

安装ipython之后,我必须重新运行easy_install才能使ipython识别模块。

Before installing ipython, I installed modules through easy_install; say sudo easy_install mechanize.

After installing ipython, I had to re-run easy_install for ipython to recognize the modules.


回答 6

遇到了类似的问题,通过调用python3而不是python进行了修复,我的模块在Python3.5中。

Had a similar problem, fixed it by calling python3 instead of python, my modules were in Python3.5.


回答 7

如果从命令行运行它,有时python解释器将不知道在何处查找模块。

下面是我的项目的目录结构:

/project/apps/..
/project/tests/..

我在以下命令下运行:

>> cd project

>> python tests/my_test.py

运行以上命令后,出现以下错误

no module named lib

lib已导入my_test.py

我打印了sys.path并发现我正在处理的项目的路径在sys.path列表中不可用

我在脚本的开头添加了以下代码my_test.py

import sys
import os

module_path = os.path.abspath(os.getcwd())    

if module_path not in sys.path:       

    sys.path.append(module_path)

我不确定这是否是解决问题的好方法,但是是的,它确实对我有用。

If you are running it from command line, sometimes python interpreter is not aware of the path where to look for modules.

Below is the directory structure of my project:

/project/apps/..
/project/tests/..

I was running below command:

>> cd project

>> python tests/my_test.py

After running above command i got below error

no module named lib

lib was imported in my_test.py

i printed sys.path and figured out that path of project i am working on is not available in sys.path list

i added below code at the start of my script my_test.py .

import sys
import os

module_path = os.path.abspath(os.getcwd())    

if module_path not in sys.path:       

    sys.path.append(module_path)

I am not sure if it is a good way of solving it but yeah it did work for me.


回答 8

这是我解决的方法:

import os
import sys
module_path = os.path.abspath(os.getcwd() + '\\..')
if module_path not in sys.path:
    sys.path.append(module_path)

This is how I fixed it:

import os
import sys
module_path = os.path.abspath(os.getcwd() + '\\..')
if module_path not in sys.path:
    sys.path.append(module_path)

回答 9

我发现此问题的解决方案已在此处广泛记录:

https://jakevdp.github.io/blog/2017/12/05/installing-python-packages-from-jupyter/

基本上,您必须在Jupyter环境中安装软件包,并发出如下shell命令:

!{sys.executable} -m pip install numpy

请检查上面的链接以获得权威的完整答案。

I have found that the solution to this problem was extensively documented here:

https://jakevdp.github.io/blog/2017/12/05/installing-python-packages-from-jupyter/

Basically, you must install the packages within the Jupyter environment, issuing shell commands like:

!{sys.executable} -m pip install numpy

Please check the above link for an authoritative full answer.


回答 10

我发现了这种差异的另一个来源:

我在本地和在virtualenvs中都安装了ipython。我的问题是,在使用ipython新建的virtualenv内部,安装了ipython系统,它与virtualenv中的python和ipython版本不同(2.7.x与3.5.x),并且随之而来。

我认为,每当安装将要安装二进制文件的东西时,明智的做法yourvirtualenv/binrehash针对正在使用的任何外壳程序立即运行或类似运行,以便获取正确的python / ipython。(必须检查是否有合适pip的安装后挂钩…)

I found yet another source of this discrepancy:

I have ipython installed both locally and in commonly in virtualenvs. My problem was that, inside a newly made virtualenv with ipython, the system ipython was picked up, which was a different version than the python and ipython in the virtualenv (a 2.7.x vs. a 3.5.x), and hilarity ensued.

I think the smart thing to do whenever installing something that will have a binary in yourvirtualenv/bin is to immediately run rehash or similar for whatever shell you are using so that the correct python/ipython gets picked up. (Gotta check if there are suitable pip post-install hooks…)


回答 11

不带脚本的解决方案:

  1. 打开Spyder->工具-> PYTHONPATH管理器
  2. 通过单击“添加路径”来添加Python路径。例如:“ C:\ Users \ User \ AppData \ Local \ Programs \ Python \ Python37 \ Lib \ site-packages”
  3. 单击“同步…”以允许其他程序(例如Jupyter Notebook)使用在步骤2中设置的pythonpaths。
  4. 如果Jupyter已打开,请重新启动

Solution without scripting:

  1. Open Spyder -> Tools -> PYTHONPATH manager
  2. Add Python paths by clicking “Add Path”. E.g: ‘C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages’
  3. Click “Synchronize…” to allow other programs (e.g. Jupyter Notebook) use the pythonpaths set in step 2.
  4. Restart Jupyter if it is open

回答 12

这可能是由系统上安装的不同python版本(即python2python3)引起的

运行命令$ pip --version$ pip3 --version检查哪个来自Python 3x。例如,您应该看到如下版本信息:

pip 19.0.3 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)

然后example.py使用以下命令运行脚本

$ python3 example.py

This is probably caused by different python versions installed on your system, i.e. python2 or python3.

Run command $ pip --version and $ pip3 --version to check which pip is from at Python 3x. E.g. you should see version information like below:

pip 19.0.3 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)

Then run the example.py script with below command

$ python3 example.py

回答 13

出现在我的目录下utils。我试图将此目录导入为:

from utils import somefile

utils已经是python中的软件包。只需将您的目录名称更改为其他名称,它就可以正常工作。

Happened to me with the directory utils. I was trying to import this directory as:

from utils import somefile

utils is already a package in python. Just change your directory name to something different and it should work just fine.


回答 14

此类错误最有可能是由于python版本冲突引起的。例如,如果您的应用程序仅在python 3上运行,并且您还获得了python 2,那么最好指定要使用的版本。例如使用

python3 .....

代替

python

This kind of errors occurs most probably due to python version conflicts. For example, if your application runs only on python 3 and you got python 2 as well, then it’s better to specify which version to use. For example use

python3 .....

instead of

python

回答 15

该答案适用于此问题,如果

  1. 您不想更改代码
  2. 您不想永久更改PYTHONPATH

临时修改PYTHONPATH

下面的路径可以是相对的

PYTHONPATH=/path/to/dir python script.py

This answer applies to this question if

  1. You don’t want to change your code
  2. You don’t want to change PYTHONPATH permanently

Temporarily modify PYTHONPATH

path below can be relative

PYTHONPATH=/path/to/dir python script.py

回答 16

导入sys sys.path.append(’/ Users / {user} /Library/Python/3.7/lib/python/site-packages’)import ta

import sys sys.path.append(‘/Users/{user}/Library/Python/3.7/lib/python/site-packages’) import ta


回答 17

删除pathlib并重新安装它。删除sitepackages文件夹中的pathlib并使用pip命令重新安装pathlib软件包:

pip install pathlib

Remove pathlib and reinstall it. Delete the pathlib in sitepackages folder and reinstall the pathlib package by using pip command:

pip install pathlib

ImportError:无法导入名称X

问题:ImportError:无法导入名称X

我有四个不同的文件,分别命名为:main,vector,entity和physics。我不会发布所有代码,而只会发布导入代码,因为我认为这就是错误所在。(如果需要,我可以发布更多信息)

主要:

import time
from entity import Ent
from vector import Vect
#the rest just creates an entity and prints the result of movement

实体:

from vector import Vect
from physics import Physics
class Ent:
    #holds vector information and id
def tick(self, dt):
    #this is where physics changes the velocity and position vectors

向量:

from math import *
class Vect:
    #holds i, j, k, and does vector math

物理:

from entity import Ent
class Physics:
    #physics class gets an entity and does physics calculations on it.

然后,我从main.py运行,出现以下错误:

Traceback (most recent call last):
File "main.py", line 2, in <module>
    from entity import Ent
File ".../entity.py", line 5, in <module>
    from physics import Physics
File ".../physics.py", line 2, in <module>
    from entity import Ent
ImportError: cannot import name Ent

我对Python非常陌生,但是已经使用C ++了很长时间。我猜测该错误是由于两次导入实体引起的,一次是在主体中,一次是在物理学中,但是我不知道解决方法。有人可以帮忙吗?

I have four different files named: main, vector, entity and physics. I will not post all the code, just the imports, because I think that’s where the error is. (If you want, I can post more)

Main:

import time
from entity import Ent
from vector import Vect
#the rest just creates an entity and prints the result of movement

Entity:

from vector import Vect
from physics import Physics
class Ent:
    #holds vector information and id
def tick(self, dt):
    #this is where physics changes the velocity and position vectors

Vector:

from math import *
class Vect:
    #holds i, j, k, and does vector math

Physics:

from entity import Ent
class Physics:
    #physics class gets an entity and does physics calculations on it.

I then run from main.py and I get the following error:

Traceback (most recent call last):
File "main.py", line 2, in <module>
    from entity import Ent
File ".../entity.py", line 5, in <module>
    from physics import Physics
File ".../physics.py", line 2, in <module>
    from entity import Ent
ImportError: cannot import name Ent

I am very new to Python but have worked with C++ for a long time. I’m guessing that the error is due to importing entity twice, once in main, and later in physics, but I don’t know a workaround. Can anyone help?


回答 0

您有循环依赖进口。physics.py从定义entity类之前导入,Entphysics尝试导入entity已初始化的类。physicsentity模块中删除对的依赖。

You have circular dependent imports. physics.py is imported from entity before class Ent is defined and physics tries to import entity that is already initializing. Remove the dependency to physics from entity module.


回答 1

虽然您绝对应该避免循环依赖,但可以推迟python中的导入。

例如:

import SomeModule

def someFunction(arg):
    from some.dependency import DependentClass

这(至少在某些情况下)将避免该错误。

While you should definitely avoid circular dependencies, you can defer imports in python.

for example:

import SomeModule

def someFunction(arg):
    from some.dependency import DependentClass

this ( at least in some instances ) will circumvent the error.


回答 2

这是一个循环依赖性。无需对代码进行任何结构修改即可解决。发生此问题的原因是,在vector您要求entity立即可用时,反之亦然。出现此问题的原因是,您要求在模块准备就绪之前通过使用来访问模块的内容from x import y。这基本上与

import x
y = x.y
del x

Python能够检测循环依赖关系并防止导入的无限循环。本质上,所有发生的事情都是为模块创建了一个空的占位符(即,它没有内容)。一旦循环依赖的模块被编译,它将更新导入的模块。这是类似的工作。

a = module() # import a

# rest of module

a.update_contents(real_a)

为了使python能够使用循环依赖关系,您必须import x仅使用样式。

import x
class cls:
    def __init__(self):
        self.y = x.y

由于您不再在顶层引用模块的内容,因此python可以编译模块,而无需实际访问循环依赖项的内容。顶层是指在编译过程中将执行的行,而不是函数的内容(例如y = x.y)。访问模块内容的静态或类变量也会引起问题。

This is a circular dependency. It can be solved without any structural modifications to the code. The problem occurs because in vector you demand that entity be made available for use immediately, and vice versa. The reason for this problem is that you asking to access the contents of the module before it is ready — by using from x import y. This is essentially the same as

import x
y = x.y
del x

Python is able to detect circular dependencies and prevent the infinite loop of imports. Essentially all that happens is that an empty placeholder is created for the module (ie. it has no content). Once the circularly dependent modules are compiled it updates the imported module. This is works something like this.

a = module() # import a

# rest of module

a.update_contents(real_a)

For python to be able to work with circular dependencies you must use import x style only.

import x
class cls:
    def __init__(self):
        self.y = x.y

Since you are no longer referring to the contents of the module at the top level, python can compile the module without actually having to access the contents of the circular dependency. By top level I mean lines that will be executed during compilation as opposed to the contents of functions (eg. y = x.y). Static or class variables accessing the module contents will also cause problems.


回答 3

弄清楚逻辑很重要。出现此问题,因为引用变成死循环。

如果您不想更改逻辑,则可以将导致ImportError的某些import语句放在文件的其他位置,例如结尾。

py

from test.b import b2

def a1():
    print('a1')
    b2()

b.py

from test.a import a1

def b1():
    print('b1')
    a1()

def b2():
    print('b2')

if __name__ == '__main__':
    b1()

您将收到导入错误: ImportError: cannot import name 'a1'

但是,如果我们改变test.b的位置,将b2导入A如下所示:

py

def a1():
    print('a1')
    b2()

from test.b import b2

我们可以得到我们想要的:

b1
a1
b2

To make logic clear is very important. This problem appear, because the reference become a dead loop.

If you don’t want to change the logic, you can put the some import statement which caused ImportError to the other position of file, for example the end.

a.py

from test.b import b2

def a1():
    print('a1')
    b2()

b.py

from test.a import a1

def b1():
    print('b1')
    a1()

def b2():
    print('b2')

if __name__ == '__main__':
    b1()

You will get Import Error: ImportError: cannot import name 'a1'

But if we change the position of from test.b import b2 in A like below:

a.py

def a1():
    print('a1')
    b2()

from test.b import b2

And the we can get what we want:

b1
a1
b2

回答 4

这是一个循环依赖性。我们可以通过在需要的地方使用导入模块或类或函数来解决此问题。如果我们使用这种方法,我们可以修复循环依赖

py

from B import b2
def a1():
    print('a1')
    b2()

py

def b1():
   from A import a1
   print('b1')
   a1()

def b2():
   print('b2')
if __name__ == '__main__':
   b1() 

This is a circular dependency. we can solve this problem by using import module or class or function where we needed. if we use this approach, we can fix circular dependency

A.py

from B import b2
def a1():
    print('a1')
    b2()

B.py

def b1():
   from A import a1
   print('b1')
   a1()

def b2():
   print('b2')
if __name__ == '__main__':
   b1() 

回答 5

我也刚收到这个错误,原因有所不同…

from my_sub_module import my_function

主脚本具有Windows行尾。my_sub_module具有UNIX行结尾。将它们更改为相同可解决此问题。它们还需要具有相同的字符编码。

I just got this error too, for a different reason…

from my_sub_module import my_function

The main script had Windows line endings. my_sub_module had UNIX line endings. Changing them to be the same fixed the problem. They also need to have the same character encoding.


回答 6

如前所述,这是由 循环依赖。尚未提及的是,当您使用Python输入模块并且仅导入用于注释 Types的类时,可以使用 Forward引用

当类型提示包含尚未定义的名称时,该定义可以表示为字符串文字,以便稍后解析。

并删除依赖项(import),例如代替

from my_module import Tree

def func(arg: Tree):
    # code

做:

def func(arg: 'Tree'):
    # code

(注意删除的import语句)

As already mentioned, this is caused by a circular dependency. What has not been mentioned is that when you’re using Python typing module and you import a class only to be used to annotate Types, you can use Forward references:

When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.

and remove the dependency (the import), e.g. instead of

from my_module import Tree

def func(arg: Tree):
    # code

do:

def func(arg: 'Tree'):
    # code

(note the removed import statement)


回答 7

不要使用您导入的其他模块的名称来命名当前的python脚本

解决方案:重命名工作的python脚本

例:

  1. 你在工作 medicaltorch.py
  2. 在该脚本中,您具有:应该from medicaltorch import datasets as mt_datasets在哪里medicaltorch安装了模块

将会失败ImportError。只需在1中重命名工作的python脚本即可。

Don’t name your current python script with the name of some other module you import

Solution: rename your working python script

Example:

  1. you are working in medicaltorch.py
  2. in that script, you have: from medicaltorch import datasets as mt_datasets where medicaltorch is supposed to be an installed module

This will fail with the ImportError. Just rename your working python script in 1.


回答 8

在这里还没有看到这个-这真是愚蠢,但是请确保您导入的是正确的变量/函数。

我收到此错误

ImportError:无法导入名称IMPLICIT_WAIT

因为我的变量实际上是IMPLICIT_TIMEOUT

当我将导入更改为使用正确的名称时,我不再收到错误🤦‍♂️

Don’t see this one here yet – this is incredibly stupid, but make sure you’re importing the correct variable/function.

I was getting this error

ImportError: cannot import name IMPLICIT_WAIT

because my variable was actually IMPLICIT_TIMEOUT.

when I changed my import to use the correct name, I no longer got the error 🤦‍♂️


回答 9

如果file1.py要从中导入file2.py并使用此功能:

if __name__ == '__main__':
    # etc

低于in的变量file1.py 不能导入file2.py因为__name__ 不相等 __main__

如果你想从进口的东西file1.pyfile2.py,你需要使用此file1.py

if __name__ == 'file1':
    # etc

如有疑问,请发表assert声明以确定是否__name__=='__main__'

If you are importing file1.py from file2.py and used this:

if __name__ == '__main__':
    # etc

Variables below that in file1.py cannot be imported to file2.py because __name__ does not equal __main__!

If you want to import something from file1.py to file2.py, you need to use this in file1.py:

if __name__ == 'file1':
    # etc

In case of doubt, make an assert statement to determine if __name__=='__main__'


回答 10

跟踪导入错误的一种方法是逐步尝试在每个导入的文件上运行python以跟踪不良文件。

  1. 你会得到类似:

    python ./main.py

    ImportError:无法导入名称A

  2. 然后您启动:

    python ./modules/a.py

    ImportError:无法导入名称B

  3. 然后您启动:

    python ./modules/b.py

    ImportError:无法导入名称C(某些不存在的模块或某些其他错误)

One way to track import error is step by step trying to run python on each of imported files to track down bad one.

  1. you get something like:

    python ./main.py
    

    ImportError: cannot import name A

  2. then you launch:

    python ./modules/a.py
    

    ImportError: cannot import name B

  3. then you launch:

    python ./modules/b.py
    

    ImportError: cannot import name C (some NON-Existing module or some other error)


回答 11

同样与OP没有直接关系,但是在向模块添加新对象后未能重新启动 PyCharm Python控制台也是一种使人非常困惑的好方法ImportError: Cannot import name ...

令人困惑的是,PyCharm 在控制台中自动完成导入,但是导入失败。

Also not directly relevant to the OP, but failing to restart a PyCharm Python console, after adding a new object to a module, is also a great way to get a very confusing ImportError: Cannot import name ...

The confusing part is that PyCharm will autocomplete the import in the console, but the import then fails.


回答 12

在我的情况下,我正在使用Jupyter笔记本工作,而发生这种情况的原因是,从我在工作文件中定义类/函数起,就已经缓存了导入。

我重新启动了Jupyter内核,错误消失了。

In my case, I was working in a Jupyter notebook and this was happening due the import already being cached from when I had defined the class/function inside my working file.

I restarted my Jupyter kernel and the error disappeared.


回答 13

不是专门针对此问询者,但是如果您导入中的类名与您要从中导入的文件中的定义不匹配,则会显示此相同错误。

Not specifically for this asker, but this same error will show if the class name in your import doesn’t match the definition in the file you’re importing from.


回答 14

问题很明显:和模块中的名称之间存在循环依赖关系。entityphysics

无论导入整个模块还是仅导入类,都必须加载名称。

观看此示例:

# a.py
import b
def foo():
  pass
b.bar()
# b.py
import a
def bar():
  pass
a.foo()

它将被编译成:

# a.py
# import b
# b.py
# import a # ignored, already importing
def bar():
  pass
a.foo()
# name a.foo is not defined!!!
# import b done!
def foo():
  pass
b.bar()
# done!

稍作更改,我们可以解决此问题:

# a.py
def foo():
  pass
import b
b.bar()
# b.py
def bar():
  pass
import a
a.foo()

它将被编译成:

# a.py
def foo():
  pass
# import b
# b.py
def bar():
  pass
# import a # ignored, already importing
a.foo()
# import b done!
b.bar()
# done!

The problem is clear: circular dependency between names in entity and physics modules.

Regardless of importing the whole module or just a class, the names must be loaded .

Watch this example:

# a.py
import b
def foo():
  pass
b.bar()
# b.py
import a
def bar():
  pass
a.foo()

This will be compiled into:

# a.py
# import b
# b.py
# import a # ignored, already importing
def bar():
  pass
a.foo()
# name a.foo is not defined!!!
# import b done!
def foo():
  pass
b.bar()
# done!

With one slight change we can solve this:

# a.py
def foo():
  pass
import b
b.bar()
# b.py
def bar():
  pass
import a
a.foo()

This will be compiled into:

# a.py
def foo():
  pass
# import b
# b.py
def bar():
  pass
# import a # ignored, already importing
a.foo()
# import b done!
b.bar()
# done!

Python错误“ ImportError:未命名模块”

问题:Python错误“ ImportError:未命名模块”

Python安装在本地目录中。

我的目录树如下所示:

(local directory)/site-packages/toolkit/interface.py

我的代码在这里:

(local directory)/site-packages/toolkit/examples/mountain.py

要运行该示例,我编写python mountain.py,并且在代码中有:

from toolkit.interface import interface

我得到错误:

Traceback (most recent call last):
  File "mountain.py", line 28, in ?
    from toolkit.interface import interface
ImportError: No module named toolkit.interface

我已经检查过了sys.path,这里有目录/site-packages。另外,我__init__.py.bin在toolkit文件夹中有该文件,以向Python指示这是一个软件包。我__init__.py.bin在示例目录中也有一个。

我不知道为什么Python在时找不到文件sys.path。有任何想法吗?可以是权限问题吗?我需要执行许可吗?

Python is installed in a local directory.

My directory tree looks like this:

(local directory)/site-packages/toolkit/interface.py

My code is in here:

(local directory)/site-packages/toolkit/examples/mountain.py

To run the example, I write python mountain.py, and in the code I have:

from toolkit.interface import interface

And I get the error:

Traceback (most recent call last):
  File "mountain.py", line 28, in ?
    from toolkit.interface import interface
ImportError: No module named toolkit.interface

I have already checked sys.path and there I have the directory /site-packages. Also, I have the file __init__.py.bin in the toolkit folder to indicate to Python that this is a package. I also have a __init__.py.bin in the examples directory.

I do not know why Python cannot find the file when it is in sys.path. Any ideas? Can it be a permissions problem? Do I need some execution permission?


回答 0

根据您对orip帖子的评论,我想这是发生了什么:

  1. __init__.py在Windows上进行了编辑。
  2. Windows编辑器添加了一些不可打印的内容,也许是回车符(Windows中的行尾是CR / LF;在Unix中是LF),或者是CTRL-Z(Windows文件末尾)。
  3. 您使用WinSCP将文件复制到Unix框中。
  4. WinSCP认为:“这不是基本文字;我将添加.bin扩展名以指示二进制数据。”
  5. 缺少__init__.py(现在称为__init__.py.bin)意味着python无法将工具包理解为一个包。
  6. __init__.py在适当的目录中创建,一切正常…?

Based on your comments to orip’s post, I guess this is what happened:

  1. You edited __init__.py on windows.
  2. The windows editor added something non-printing, perhaps a carriage-return (end-of-line in Windows is CR/LF; in unix it is LF only), or perhaps a CTRL-Z (windows end-of-file).
  3. You used WinSCP to copy the file to your unix box.
  4. WinSCP thought: “This has something that’s not basic text; I’ll put a .bin extension to indicate binary data.”
  5. The missing __init__.py (now called __init__.py.bin) means python doesn’t understand toolkit as a package.
  6. You create __init__.py in the appropriate directory and everything works… ?

回答 1

是否

(local directory)/site-packages/toolkit

有一个__init__.py

为了使进口步行通过你的目录中的每个目录必须有一个__init__.py文件。

Does

(local directory)/site-packages/toolkit

have a __init__.py?

To make import walk through your directories every directory must have a __init__.py file.


回答 2

我在LPTHW中进行此练习时遇到了非常相似的事情。我永远无法让Python识别出我正在从其调用的目录中有文件。但是我最终能够使它工作。我所做的以及我的建议是尝试以下操作:

(注意:从您的第一篇文章中,我假设您使用的是基于* NIX的计算机,并且正在通过命令行运行,因此此建议是针对性的。自从我运行Ubuntu以来,我就是这样做的。)

1)将目录(cd)更改为文件所在目录上方的目录。在这种情况下,您将尝试运行mountain.py文件,并尝试调用toolkit.interface.py位于单独目录中的模块。在这种情况下,您将转到包含两个文件路径的目录(或换句话说,这两个文件的路径共享的最近目录)。在这种情况下是toolkit目录。

2)在tookit目录中时,在命令行上输入以下代码行:

export PYTHONPATH=.

这会将您的PYTHONPATH设置为“。”,这基本上意味着您的PYTHONPATH现在将在您当前所在目录(甚至更重要的是,您所在目录的子目录分支)中查找所有被调用的文件。因此,它不只是看在你的当前目录,但在所有可在目录中的当前目录)。

3)在上述步骤中设置完PYTHONPATH之后,请从当前目录(该toolkit目录)运行模块。Python现在应该找到并加载您指定的模块。

希望这可以帮助。我自己对此感到非常沮丧。

I ran into something very similar when I did this exercise in LPTHW; I could never get Python to recognise that I had files in the directory I was calling from. But I was able to get it to work in the end. What I did, and what I recommend, is to try this:

(NOTE: From your initial post, I am assuming you are using an *NIX-based machine and are running things from the command line, so this advice is tailored to that. Since I run Ubuntu, this is what I did)

1) Change directory (cd) to the directory above the directory where your files are. In this case, you’re trying to run the mountain.py file, and trying to call the toolkit.interface.py module, which are in separate directories. In this case, you would go to the directory that contains paths to both those files (or in other words, the closest directory that the paths of both those files share). Which in this case is the toolkit directory.

2) When you are in the tookit directory, enter this line of code on your command line:

export PYTHONPATH=.

This sets your PYTHONPATH to “.”, which basically means that your PYTHONPATH will now look for any called files within the directory you are currently in, (and more to the point, in the sub-directory branches of the directory you are in. So it doesn’t just look in your current directory, but in all the directories that are in your current directory).

3) After you’ve set your PYTHONPATH in the step above, run your module from your current directory (the toolkit directory). Python should now find and load the modules you specified.

Hope this helps. I was quite frustrated with this myself.


回答 3

在* nix上,还要确保正确配置了PYTHONPATH,尤其是它具有以下格式:

 .:/usr/local/lib/python

(请注意.:开头,以便它也可以在当前目录中搜索。)

它也可能在其他位置,具体取决于版本:

 .:/usr/lib/python
 .:/usr/lib/python2.6
 .:/usr/lib/python2.7 and etc.

On *nix, also make sure that PYTHONPATH is configured correctly, especially that it has this format:

 .:/usr/local/lib/python

(Mind the .: at the beginning, so that it can search on the current directory, too.)

It may also be in other locations, depending on the version:

 .:/usr/lib/python
 .:/usr/lib/python2.6
 .:/usr/lib/python2.7 and etc.

回答 4

我解决了自己的问题,并将总结出错误的地方和解决方案:

该文件需要完全调用__init__.py。如果扩展名不同(例如在我的情况下),.py.bin则Python无法在目录中移动,因此找不到模块。要编辑文件,您需要使用Linux编辑器,例如vinano。如果您使用Windows编辑器,则会写一些隐藏的字符。

影响它的另一个问题是,我的根目录安装了另一个Python版本,因此,如果有人正在使用python的本地安装,请确保运行程序的Python安装是本地Python。要检查这一点,只需执行which python,然后查看可执行文件是否在您的本地目录中。如果不是,请更改路径,但请确保本地Python目录位于另一个Python目录之前。

I solved my own problem, and I will write a summary of the things that were wrong and the solution:

The file needs to be called exactly __init__.py. If the extension is different such as in my case .py.bin then Python cannot move through the directories and then it cannot find the modules. To edit the files you need to use a Linux editor, such as vi or nano. If you use a Windows editor this will write some hidden characters.

Another problem that was affecting it was that I had another Python version installed by the root, so if someone is working with a local installation of python, be sure that the Python installation that is running the programs is the local Python. To check this, just do which python, and see if the executable is the one that is in your local directory. If not, change the path, but be sure that the local Python directory is before than the other Python.


回答 5

一个简单的解决方案是使用来安装模块,python -m pip install <library-name>而不是pip install <library-name> 在管理员限制的情况下使用sudo

an easy solution is to install the module using python -m pip install <library-name> instead of pip install <library-name> you may use sudo in case of admin restrictions


回答 6

要将目录标记为包,您需要一个名为的文件__init__.py,这有帮助吗?

To mark a directory as a package you need a file named __init__.py, does this help?


回答 7

使用PyCharm(属于JetBrains套件的一部分),您需要将脚本目录定义为Source:
Right Click > Mark Directory as > Sources Root

Using PyCharm (part of the JetBrains suite) you need to define your script directory as Source:
Right Click > Mark Directory as > Sources Root


回答 8

您正在阅读此答案,表明您__init__.py来对地方了,已经安装了所有依赖项,并且仍在获取ImportError

我遇到了类似的问题,除了我的程序在使用PyCharm运行时可以正常运行,但是当我从终端运行时出现上述错误。进一步挖掘之后,我发现PYTHONPATH该项目目录中没有该条目。因此,我将PYTHONPATH每个Import语句设置为在PyCharm上有效,但不能在terminal上使用

export PYTHONPATH=$PYTHONPATH:`pwd`  (OR your project root directory)

使用sys.pathas 的另一种方法是:

import sys
sys.path.insert(0,'<project directory>') OR
sys.path.append('<project directory>')

您可以根据要搜索项目的顺序使用插入/追加。

You are reading this answer says that your __init__.py is in the right place, you have installed all the dependencies and you are still getting the ImportError.

I was facing a similar issue except that my program would run fine when ran using PyCharm but the above error when I would run it from the terminal. After digging further, I found out that PYTHONPATH didn’t have the entry for the project directory. So, I set PYTHONPATH per Import statement works on PyCharm but not from terminal:

export PYTHONPATH=$PYTHONPATH:`pwd`  (OR your project root directory)

There’s another way to do this using sys.path as:

import sys
sys.path.insert(0,'<project directory>') OR
sys.path.append('<project directory>')

You can use insert/append based on the order in which you want your project to be searched.


回答 9

对我来说,那真是愚蠢。我使用来安装该库,pip3 install但正在运行程序python program.py而不是python3 program.py

For me, it was something really stupid. I installed the library using pip3 install but was running my program as python program.py as opposed to python3 program.py.


回答 10

对。您需要包含该__init__.py文件的目录,该文件是用于初始化程序包的文件。在这里,看看这个

__init__.py文件是使Python将目录视为包含包所必需的;这样做是为了防止具有通用名称的目录(例如字符串)无意间隐藏了稍后在模块搜索路径中出现的有效模块。在最简单的情况下,__init__.py可以只是一个空文件,但它也可以为该程序包执行初始化代码或设置__all__变量,如后所述。

Yup. You need the directory to contain the __init__.py file, which is the file that initializes the package. Here, have a look at this.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.


回答 11

  1. 您必须在与要导入文件相同的目录中拥有文件__ init__.py。
  2. 您不能尝试从PYTHONPATH上配置的2个文件夹中导入具有相同名称的文件。

例如:/ etc / environment

PYTHONPATH = $ PYTHONPATH:/ opt /文件夹1:/ opt /文件夹2

/ opt / folder1 / foo

/ opt / folder2 / foo

并且,如果您尝试导入foo文件,python将不知道您要哪个。

从foo import … >>> importerror:没有名为foo的模块

  1. You must have the file __ init__.py in the same directory where it’s the file that you are importing.
  2. You can not try to import a file that has the same name and be a file from 2 folders configured on the PYTHONPATH.

eg: /etc/environment

PYTHONPATH=$PYTHONPATH:/opt/folder1:/opt/folder2

/opt/folder1/foo

/opt/folder2/foo

And, if you are trying to import foo file, python will not know which one you want.

from foo import … >>> importerror: no module named foo


回答 12

我的两分钱:

吐:

Traceback (most recent call last):
      File "bash\bash.py", line 454, in main
        import bosh
      File "Wrye Bash Launcher.pyw", line 63, in load_module
        mod = imp.load_source(fullname,filename+ext,fp)
      File "bash\bosh.py", line 69, in <module>
        from game.oblivion.RecordGroups import MobWorlds, MobDials, MobICells, \
    ImportError: No module named RecordGroups

这让我很困惑-遍历各种帖子,暗示了丑陋的syspath hacks(如您所见,我__init__.py在那里)。好吧,事实证明game / oblivion.py和game / oblivion混淆了python,并吐出了相当无用的“没有名为RecordGroups的模块”。我对解决此问题和/或记录此(相同名称)行为的链接感兴趣->编辑(2017.01.24)-看看如果我具有相同名称的模块和软件包怎么办?有趣的是,通常程序包具有优先权,但显然我们的启动程序违反了此规则。

编辑(2015.01.17):我没有提到我们使用此处剖析的自定义启动器

My two cents:

Spit:

Traceback (most recent call last):
      File "bash\bash.py", line 454, in main
        import bosh
      File "Wrye Bash Launcher.pyw", line 63, in load_module
        mod = imp.load_source(fullname,filename+ext,fp)
      File "bash\bosh.py", line 69, in <module>
        from game.oblivion.RecordGroups import MobWorlds, MobDials, MobICells, \
    ImportError: No module named RecordGroups

This confused the hell out of me – went through posts and posts suggesting ugly syspath hacks (as you see my __init__.py were all there). Well turns out that game/oblivion.py and game/oblivion was confusing python which spit out the rather unhelpful “No module named RecordGroups”. I’d be interested in a workaround and/or links documenting this (same name) behavior -> EDIT (2017.01.24) – have a look at What If I Have a Module and a Package With The Same Name? Interestingly normally packages take precedence but apparently our launcher violates this.

EDIT (2015.01.17): I did not mention we use a custom launcher dissected here.


回答 13

Linux:导入的模块位于/usr/local/lib/python2.7/dist-packages中

如果您使用的是用C语言编译的模块,请不要忘了在之后对.so文件进行chmod修改sudo setup.py install

sudo chmod 755 /usr/local/lib/python2.7/dist-packages/*.so

Linux: Imported modules are located in /usr/local/lib/python2.7/dist-packages

If you’re using a module compiled in C, don’t forget to chmod the .so file after sudo setup.py install.

sudo chmod 755 /usr/local/lib/python2.7/dist-packages/*.so

回答 14

就我而言,问题是我链接到debug pythonboost::Python,它要求扩展名是FooLib_d.pyd,而不仅仅是FooLib.pyd; 重命名文件或更新CMakeLists.txt属性可修复该错误。

In my case, the problem was I was linking to debug python & boost::Python, which requires that the extension be FooLib_d.pyd, not just FooLib.pyd; renaming the file or updating CMakeLists.txt properties fixed the error.


回答 15

如果您尝试了上面提供的所有方法但都失败了,则也许您的模块内置模块具有相同的名称。或者,文件夹中存在的同名sys.path模块比模块具有更高的优先级。

要调试,请说出您的from foo.bar import baz抱怨ImportError: No module named bar。更改为import foo; print foo,将显示的路径foo。是您所期望的吗?

如果不是,请重命名foo或使用绝对导入

If you have tried all methods provided above but failed, maybe your module has the same name as a built-in module. Or, a module with the same name existing in a folder that has a high priority in sys.path than your module’s.

To debug, say your from foo.bar import baz complaints ImportError: No module named bar. Changing to import foo; print foo, which will show the path of foo. Is it what you expect?

If not, Either rename foo or use absolute imports.


回答 16

我的问题是,__init__.py实际上需要添加其父目录时,我将带有文件的目录添加到了PYTHONPATH中。

My problem was that I added the directory with the __init__.py file to PYTHONPATH, when actually I needed to add its parent directory.


回答 17

对于所有仍然有此问题的人。我相信Pycharm与进口商品混淆了。对我来说,当我写“从命名空间导入某物”时,前一行用红色下划线标出,表示有错误,但可以。但是,“从.namespace导入某些内容”不会带有下划线,但也无法正常工作。

尝试

try:
    from namespace import something 
except NameError:
    from .namespace import something

To all those who still have this issue. I believe Pycharm gets confused with imports. For me, when i write ‘from namespace import something’, the previous line gets underlined in red, signaling that there is an error, but works. However ”from .namespace import something’ doesn’t get underlined, but also doesn’t work.

Try

try:
    from namespace import something 
except NameError:
    from .namespace import something

回答 18

通过编写修复了我的问题print (sys.path),发现尽管进行了全新安装,python仍在使用过期的软件包。删除这些使python自动使用正确的软件包。

Fixed my issue by writing print (sys.path) and found out that python was using out of date packages despite a clean install. Deleting these made python automatically use the correct packages.


回答 19

就我而言,因为我正在使用PyCharm和PyCharm在项目文件夹中为每个项目创建一个“ venv”,但这只是python的一个迷你环境。尽管您已经在Python中安装了所需的库,但是在您的自定义项目“ venv”中,该库不可用。这是PyCharm中发生“导入错误:没有名为xxxxxx的模块”的真正原因。要解决此问题,必须通过以下步骤将库添加到项目自定义环境中:

  • 在PyCharm中,从菜单“文件”->“设置”
  • 在设置对话框中,项目:XXXProject->项目解释器
  • 点击“添加”按钮,它将显示“可用包”对话框
  • 搜索您的库,单击“安装软件包”
  • 然后,所有需要的软件包将安装在项目自定义“ venv”文件夹中。

请享用。

In my case, because I’m using PyCharm and PyCharm create a ‘venv’ for every project in project folder, but it is only a mini env of python. Although you have installed the libraries you need in Python, but in your custom project ‘venv’, it is not available. This is the real reason of ‘ImportError: No module named xxxxxx’ occurred in PyCharm. To resolve this issue, you must add libraries to your project custom env by these steps:

  • In PyCharm, from menu ‘File’->Settings
  • In Settings dialog, Project: XXXProject->Project Interpreter
  • Click “Add” button, it will show you ‘Available Packages’ dialog
  • Search your library, click ‘Install Package’
  • Then, all you needed package will be installed in you project custom ‘venv’ folder.

Enjoy.


回答 20

在经历了同样的问题后,我发现我的解决方案是pyc从项目中删除所有文件,似乎这些缓存的文件以某种方式导致了此错误。

我发现最简单的方法是在Windows资源管理器中导航到我的项目文件夹并搜索*.pyc,然后选择所有(Ctrl+ A)并删除它们(Ctrl+ X)。

可能我可以通过删除特定pyc文件来解决问题,但我从未尝试过

After just suffering the same issue I found my resolution was to delete all pyc files from my project, it seems like these cached files were somehow causing this error.

Easiest way I found to do this was to navigate to my project folder in Windows explorer and searching for *.pyc, then selecting all (Ctrl+A) and deleting them (Ctrl+X).

Its possible I could have resolved my issues by just deleting the specific pyc file but I never tried this


回答 21

我遇到了同样的问题:Import error。此外,该库已正确安装了100%。问题的根源是在我的PC 3版本上安装了python(anaconda数据包)。这就是为什么没有将库安装到正确的位置的原因。之后,我只是在我的IDE PyCharm中更改为python的正确版本。

I faced the same problem: Import error. In addition the library’ve been installed 100% correctly. The source of the problem was that on my PC 3 version of python (anaconda packet) have been installed). This is why the library was installed no to the right place. After that I just changed to the proper version of python in the my IDE PyCharm.


回答 22

我有同样的错误。这是因为有人在与脚本相同的文件夹中创建了一个文件夹,该文件夹的名称与我从其他位置导入的模块冲突。它没有导入外部模块,而是查看了该文件夹内部,该文件夹显然不包含预期的模块。

I had the same error. It was caused by somebody creating a folder in the same folder as my script, the name of which conflicted with a module I was importing from elsewhere. Instead of importing the external module, it looked inside this folder which obviously didn’t contain the expected modules.


回答 23

我遇到了同样的问题(Python 2.7 Linux),我找到了解决方案,我想分享一下。就我而言,我的结构如下:

Booklet
-> __init__.py
-> Booklet.py
-> Question.py
default
-> __init_.py
-> main.py

在“ main.py”中,我尝试了以下所有组合,但均未成功:

from Booklet import Question
from Question import Question
from Booklet.Question import Question
from Booklet.Question import *
import Booklet.Question
# and many othet various combinations ...

解决方案比我想象的要简单得多。我将文件夹“ Booklet”重命名为“ booklet”,仅此而已。现在,Python可以通过在“ main.py”中使用以下代码来正常导入Question类:

from booklet.Booklet import Booklet
from booklet.Question import Question
from booklet.Question import AnotherClass

由此我可以得出结论,像“小册子”之类的包名称(文件夹)必须以小写开头,否则Python会将其与类名和文件名混淆。

显然,这不是您的问题,但是John Fouhy的回答非常好,并且该线程具有几乎所有可能导致此问题的东西。因此,这是一回事,我希望这可以对其他人有所帮助。

I had the same problem (Python 2.7 Linux), I have found the solution and i would like to share it. In my case i had the structure below:

Booklet
-> __init__.py
-> Booklet.py
-> Question.py
default
-> __init_.py
-> main.py

In ‘main.py’ I had tried unsuccessfully all the combinations bellow:

from Booklet import Question
from Question import Question
from Booklet.Question import Question
from Booklet.Question import *
import Booklet.Question
# and many othet various combinations ...

The solution was much more simple than I thought. I renamed the folder “Booklet” into “booklet” and that’s it. Now Python can import the class Question normally by using in ‘main.py’ the code:

from booklet.Booklet import Booklet
from booklet.Question import Question
from booklet.Question import AnotherClass

From this I can conclude that Package-Names (folders) like ‘booklet’ must start from lower-case, else Python confuses it with Class names and Filenames.

Apparently, this was not your problem, but John Fouhy’s answer is very good and this thread has almost anything that can cause this issue. So, this is one more thing and I hope that maybe this could help others.


回答 24

就我而言,我要包含package.egg文件夹的路径,而不是其下面的实际软件包。我将软件包复制到顶层,并且可以正常工作。

In my case I was including the path to package.egg folder rather than the actual package underneath. I copied the package to top level and it worked.


回答 25

这对我有用:__init__.py在父文件夹中创建文件(在您的情况下,在site-packages文件夹中)。并像这样导入:

from site-packages.toolkit.interface import interface

希望它对您也有用!

This worked for me: Created __init__.py file inside parent folder (in your case, inside site-packages folder). And imported like this:

from site-packages.toolkit.interface import interface

Hope it will be useful for you as well !


回答 26

在linux服务器上尝试 dos2unix script_name

pyc使用命令删除所有(如果有的话)文件find . -name '*.pyc' -delete

如果您在Windows上处理脚本,请重新运行

In linux server try dos2unix script_name

(remove all (if there is any) pyc files with command find . -name '*.pyc' -delete)

and re run in the case if you worked on script on windows


回答 27

就我而言,我是sys.path.insert()用来导入本地模块的,并且是module not found从另一个库中获取的。我不得不把sys.path.insert()进口的商品放在下面module not found。我想最好的做法是放在sys.path.insert()进口的底部。

In my case, I was using sys.path.insert() to import a local module and was getting module not found from a different library. I had to put sys.path.insert() below the imports that reported module not found. I guess the best practice is to put sys.path.insert() at the bottom of your imports.


即使使用__init__.py,也如何解决“尝试以非软件包方式进行相对导入”

问题:即使使用__init__.py,也如何解决“尝试以非软件包方式进行相对导入”

我正在尝试使用以下目录结构来遵循PEP 328

pkg/
  __init__.py
  components/
    core.py
    __init__.py
  tests/
    core_test.py
    __init__.py

core_test.py我有以下进口声明

from ..components.core import GameLoopEvents

但是,当我运行时,出现以下错误:

tests$ python core_test.py 
Traceback (most recent call last):
  File "core_test.py", line 3, in <module>
    from ..components.core import GameLoopEvents
ValueError: Attempted relative import in non-package

到处搜索时,我发现“ 即使使用__init__.py,相对路径也无法使用 ”和“ 从相对路径导入模块 ”,但是它们没有帮助。

我在这里想念什么吗?

I’m trying to follow PEP 328, with the following directory structure:

pkg/
  __init__.py
  components/
    core.py
    __init__.py
  tests/
    core_test.py
    __init__.py

In core_test.py I have the following import statement

from ..components.core import GameLoopEvents

However, when I run, I get the following error:

tests$ python core_test.py 
Traceback (most recent call last):
  File "core_test.py", line 3, in <module>
    from ..components.core import GameLoopEvents
ValueError: Attempted relative import in non-package

Searching around I found “relative path not working even with __init__.py” and “Import a module from a relative path” but they didn’t help.

Is there anything I’m missing here?


回答 0

是。您没有将其用作包装。

python -m pkg.tests.core_test

Yes. You’re not using it as a package.

python -m pkg.tests.core_test

回答 1

详细阐述伊格纳西奥·巴斯克斯·阿布拉姆斯答案:

Python导入机制相对于__name__当前文件起作用。直接执行文件时,它没有通常的名称,但是具有"__main__"以它的名称命名。因此,相对进口无效。

您可以按照Igancio的建议使用该-m选项执行它。如果包的一部分要作为脚本运行,则还可以使用__package__属性告诉该文件在包层次结构中应具有的名称。

参见http://www.python.org/dev/peps/pep-0366/详细信息,。

To elaborate on Ignacio Vazquez-Abrams’s answer:

The Python import mechanism works relative to the __name__ of the current file. When you execute a file directly, it doesn’t have its usual name, but has "__main__" as its name instead. So relative imports don’t work.

You can, as Igancio suggested, execute it using the -m option. If you have a part of your package that is meant to be run as a script, you can also use the __package__ attribute to tell that file what name it’s supposed to have in the package hierarchy.

See http://www.python.org/dev/peps/pep-0366/ for details.


回答 2

import components.core如果将当前目录附加到,则可以直接使用sys.path

if __name__ == '__main__' and __package__ is None:
    from os import sys, path
    sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))

You can use import components.core directly if you append the current directory to sys.path:

if __name__ == '__main__' and __package__ is None:
    from os import sys, path
    sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))

回答 3

这取决于您要如何启动脚本。

如果要以经典方式从命令行启动UnitTest,那就是:

python tests/core_test.py

然后,由于在这种情况下‘components’‘tests’是同级文件夹,因此您可以使用sys.path模块的insertappend方法导入相关模块。就像是:

import sys
from os import path
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
from components.core import GameLoopEvents

否则,您可以使用’-m’参数启动脚本(请注意,在这种情况下,我们正在谈论一个软件包,因此,您不能使用‘.py’扩展名),即:

python -m pkg.tests.core_test

在这种情况下,您可以像以前一样简单地使用相对导入:

from ..components.core import GameLoopEvents

最后,您可以将两种方法混合使用,以便您的脚本无论调用方式如何都可以正常工作。例如:

if __name__ == '__main__':
    if __package__ is None:
        import sys
        from os import path
        sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
        from components.core import GameLoopEvents
    else:
        from ..components.core import GameLoopEvents

It depends on how you want to launch your script.

If you want to launch your UnitTest from the command line in a classic way, that is:

python tests/core_test.py

Then, since in this case ‘components’ and ‘tests’ are siblings folders, you can import the relative module either using the insert or the append method of the sys.path module. Something like:

import sys
from os import path
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
from components.core import GameLoopEvents

Otherwise, you can launch your script with the ‘-m’ argument (note that in this case, we are talking about a package, and thus you must not give the ‘.py’ extension), that is:

python -m pkg.tests.core_test

In such a case, you can simply use the relative import as you were doing:

from ..components.core import GameLoopEvents

You can finally mix the two approaches, so that your script will work no matter how it is called. For example:

if __name__ == '__main__':
    if __package__ is None:
        import sys
        from os import path
        sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
        from components.core import GameLoopEvents
    else:
        from ..components.core import GameLoopEvents

回答 4

在core_test.py中,执行以下操作:

import sys
sys.path.append('../components')
from core import GameLoopEvents

In core_test.py, do the following:

import sys
sys.path.append('../components')
from core import GameLoopEvents

回答 5

如果您的用例是用于运行测试的,并且可以接缝,那么您可以执行以下操作。不要像python core_test.py使用那样运行测试框架来运行测试脚本pytest。然后在命令行上您可以输入

$$ py.test

这将在您的目录中运行测试。这得到周围人的问题__name__的存在__main__,是由@BrenBarn指出。接下来,将一个空__init__.py文件放入您的测试目录,这将使测试目录成为您程序包的一部分。那你就可以做

from ..components.core import GameLoopEvents

但是,如果您将测试脚本作为主程序运行,那么事情将再次失败。因此,只需使用测试运行器。也许这也适用于其他测试运行程序,例如,nosetests但我尚未检查。希望这可以帮助。

If your use case is for running tests, and it seams that it is, then you can do the following. Instead of running your test script as python core_test.py use a testing framework such as pytest. Then on the command line you can enter

$$ py.test

That will run the tests in your directory. This gets around the issue of __name__ being __main__ that was pointed out by @BrenBarn. Next, put an empty __init__.py file into your test directory, this will make the test directory part of your package. Then you will be able to do

from ..components.core import GameLoopEvents

However, if you run your test script as a main program then things will fail once again. So just use the test runner. Maybe this also works with other test runners such as nosetests but i haven’t checked it. Hope this helps.


回答 6

我的快速解决方案是将目录添加到路径:

import sys
sys.path.insert(0, '../components/')

My quick-fix is to add the directory to the path:

import sys
sys.path.insert(0, '../components/')

回答 7

问题在于您的测试方法,

你试过了 python core_test.py

那么您将收到此错误 ValueError:尝试在非包中进行相对导入

原因:您正在从非包装来源测试包装。

因此,请从软件包源测试模块。

如果这是您的项目结构,

pkg/
  __init__.py
  components/
    core.py
    __init__.py
  tests/
    core_test.py
    __init__.py

cd pkg

python -m tests.core_test # dont use .py

或从外部pkg /

python -m pkg.tests.core_test

.如果要从同一目录中的文件夹导入,则为Single 。每退一步,再增加一个。

hi/
  hello.py
how.py

how.py

from .hi import hello

如果你想从hello.py导入

from .. import how

Issue is with your testing method,

you tried python core_test.py

then you will get this error ValueError: Attempted relative import in non-package

Reason: you are testing your packaging from non-package source.

so test your module from package source.

if this is your project structure,

pkg/
  __init__.py
  components/
    core.py
    __init__.py
  tests/
    core_test.py
    __init__.py

cd pkg

python -m tests.core_test # dont use .py

or from outside pkg/

python -m pkg.tests.core_test

single . if you want to import from folder in same directory . for each step back add one more.

hi/
  hello.py
how.py

in how.py

from .hi import hello

incase if you want to import how from hello.py

from .. import how

回答 8

旧线程。我发现__all__= ['submodule', ...]__init__.py文件中添加,然后from <CURRENT_MODULE> import *在目标中使用可以正常工作。

Old thread. I found out that adding an __all__= ['submodule', ...] to the __init__.py file and then using the from <CURRENT_MODULE> import * in the target works fine.


回答 9

您可以使用from pkg.components.core import GameLoopEvents,例如我使用pycharm,下面是我的项目结构图像,我只是从根包中导入,然后就可以了:

You can use from pkg.components.core import GameLoopEvents, for example I use pycharm, the below is my project structure image, I just import from the root package, then it works:


回答 10

正如Paolo所说,我们有2种调用方法:

1) python -m tests.core_test
2) python tests/core_test.py

它们之间的区别是sys.path [0]字符串。由于解释将在导入时搜索sys.path,因此我们可以使用tests/core_test.py

if __name__ == '__main__':
    import sys
    from pathlib import Path
    sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
    from components import core
    <other stuff>

之后,我们可以使用其他方法运行core_test.py:

cd tests
python core_test.py
python -m core_test
...

注意,py36仅经过测试。

As Paolo said, we have 2 invocation methods:

1) python -m tests.core_test
2) python tests/core_test.py

One difference between them is sys.path[0] string. Since the interpret will search sys.path when doing import, we can do with tests/core_test.py:

if __name__ == '__main__':
    import sys
    from pathlib import Path
    sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
    from components import core
    <other stuff>

And more after this, we can run core_test.py with other methods:

cd tests
python core_test.py
python -m core_test
...

Note, py36 tested only.


回答 11

这种方法对我有用,并且比某些解决方案更混乱:

try:
  from ..components.core import GameLoopEvents
except ValueError:
  from components.core import GameLoopEvents

父目录位于我的PYTHONPATH中,并且__init__.py父目录和此目录中都有文件。

上面的代码始终在python 2中有效,但是python 3有时会遇到ImportError或ModuleNotFoundError(后者在python 3.6中是新功能,是ImportError的子类),因此以下调整对我在python 2和3中均有效:

try:
  from ..components.core import GameLoopEvents
except ( ValueError, ImportError):
  from components.core import GameLoopEvents

This approach worked for me and is less cluttered than some solutions:

try:
  from ..components.core import GameLoopEvents
except ValueError:
  from components.core import GameLoopEvents

The parent directory is in my PYTHONPATH, and there are __init__.py files in the parent directory and this directory.

The above always worked in python 2, but python 3 sometimes hit an ImportError or ModuleNotFoundError (the latter is new in python 3.6 and a subclass of ImportError), so the following tweak works for me in both python 2 and 3:

try:
  from ..components.core import GameLoopEvents
except ( ValueError, ImportError):
  from components.core import GameLoopEvents

回答 12

尝试这个

import components
from components import *

Try this

import components
from components import *

回答 13

如果有人正在寻找解决方法,我偶然发现了一个。这里有一些背景。我想测试文件中的一种方法。当我从内部运行时

if __name__ == "__main__":

它总是抱怨相对进口。我尝试应用上述解决方案,但由于许多嵌套文件,每个文件都有多个导入,因此无法正常工作。

这就是我所做的。我刚刚创建了一个启动器,一个外部程序,它将导入必要的方法并调用它们。虽然这不是一个很好的解决方案,但它可以工作。

If someone is looking for a workaround, I stumbled upon one. Here’s a bit of context. I wanted to test out one of the methods I’ve in a file. When I run it from within

if __name__ == "__main__":

it always complained of the relative imports. I tried to apply the above solutions, but failed to work, since there were many nested files, each with multiple imports.

Here’s what I did. I just created a launcher, an external program that would import necessary methods and call them. Though, not a great solution, it works.


回答 14

这是一种会惹恼所有人但效果很好的方法。在测试中运行:

ln -s ../components components

然后只需像往常一样导入组件。

Here’s one way which will piss off everyone but work pretty well. In tests run:

ln -s ../components components

Then just import components like you normally would.


回答 15

这非常令人困惑,如果您使用的是像pycharm这样的IDE,那就更令人困惑了。对我有用的方法:1.进行pycharm项目设置(如果从VE或python目录运行python)2.定义的方式没有错。有时它与from folder1.file1导入类一起使用

如果它不起作用,请使用import folder1.file1。3.您的环境变量应在系统中正确提及或在命令行参数中提供。

This is very confusing, and if you are using IDE like pycharm, it’s little more confusing. What worked for me: 1. Make pycharm project settings (if you are running python from a VE or from python directory) 2. There is no wrong the way you defined. sometime it works with from folder1.file1 import class

if it does not work, use import folder1.file1 3. Your environment variable should be correctly mentioned in system or provide it in your command line argument.


回答 16

由于您的代码包含if __name__ == "__main__",而不会作为包导入,因此最好使用它sys.path.append()来解决问题。

Because your code contains if __name__ == "__main__", which doesn’t be imported as a package, you’d better use sys.path.append() to solve the problem.


从其他文件夹导入文件

问题:从其他文件夹导入文件

我有以下文件夹结构。

application/app/folder/file.py

我想从位于另一个Python文件中的file.py导入一些功能

application/app2/some_folder/some_file.py

我试过了

from application.app.folder.file import func_name

和其他一些尝试,但到目前为止,我无法正确导入。我怎样才能做到这一点?

I have the following folder structure.

application/app/folder/file.py

and I want to import some functions from file.py in another Python file which resides in

application/app2/some_folder/some_file.py

I’ve tried

from application.app.folder.file import func_name

and some other various attempts but so far I couldn’t manage to import properly. How can I do this?


回答 0

默认情况下,您不能这样做。导入文件时,Python仅搜索当前目录,入口点脚本运行sys.path所在的目录,并且包括诸如软件包安装目录之类的位置(实际上比这稍微复杂一点,但这涵盖了大多数情况) 。

但是,您可以在运行时添加到Python路径:

# some_file.py
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, '/path/to/application/app/folder')

import file

By default, you can’t. When importing a file, Python only searches the current directory, the directory that the entry-point script is running from, and sys.path which includes locations such as the package installation directory (it’s actually a little more complex than this, but this covers most cases).

However, you can add to the Python path at runtime:

# some_file.py
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, '/path/to/application/app/folder')

import file

回答 1

没错:

from application.app.folder.file import func_name

只要确保folder还包含一个__init__.py,就可以将其作为软件包包含在内。不知道为什么其他答案在谈论PYTHONPATH

Nothing wrong with:

from application.app.folder.file import func_name

Just make sure folder also contains an __init__.py, this allows it to be included as a package. Not sure why the other answers talk about PYTHONPATH.


回答 2

当模块处于并行位置时,如下所示:

application/app2/some_folder/some_file.py
application/app2/another_folder/another_file.py

该简写使一个模块对另一模块可见:

import sys
sys.path.append('../')

When modules are in parallel locations, as in the question:

application/app2/some_folder/some_file.py
application/app2/another_folder/another_file.py

This shorthand makes one module visible to the other:

import sys
sys.path.append('../')

回答 3

首先在name-file.py中导入sys

 import sys

第二个将文件夹路径附加到name-file.py中

sys.path.insert(0, '/the/folder/path/name-package/')

第三步在子目录中创建一个名为__ init __.py的空白文件(这告诉Python它是一个包)

  • 名称文件
  • 名称包
    • __初始化__.py
    • 名称模块

第四次将模块导入name-file.py文件夹内

from name-package import name-module

First import sys in name-file.py

 import sys

Second append the folder path in name-file.py

sys.path.insert(0, '/the/folder/path/name-package/')

Third Make a blank file called __ init __.py in your subdirectory (this tells Python it is a package)

  • name-file.py
  • name-package
    • __ init __.py
    • name-module.py

Fourth import the module inside the folder in name-file.py

from name-package import name-module

回答 4

我认为,一种临时方法是使用文档中所述的环境变量PYTHONPATHPython2Python3

# Linux & OSX
export PYTHONPATH=$HOME/dirWithScripts/:$PYTHONPATH

# Windows
set PYTHONPATH=C:\path\to\dirWithScripts\;%PYTHONPATH%

I think an ad-hoc way would be to use the environment variable PYTHONPATH as described in the documentation: Python2, Python3

# Linux & OSX
export PYTHONPATH=$HOME/dirWithScripts/:$PYTHONPATH

# Windows
set PYTHONPATH=C:\path\to\dirWithScripts\;%PYTHONPATH%

回答 5

这里的答案不够明确,已在Python 3.6上进行了测试

使用此文件夹结构:

main.py
|
---- myfolder/myfile.py

myfile.py内容在哪里:

def myfunc():
    print('hello')

中的导入语句main.py为:

from myfolder.myfile import myfunc
myfunc()

这将打印你好

The answers here are lacking in clarity, this is tested on Python 3.6

With this folder structure:

main.py
|
---- myfolder/myfile.py

Where myfile.py has the content:

def myfunc():
    print('hello')

The import statement in main.py is:

from myfolder.myfile import myfunc
myfunc()

and this will print hello.


回答 6

您的问题是Python正在Python目录中查找此文件,但找不到它。您必须指定所谈论的目录是您所在的目录,而不是Python目录。

为此,您可以更改以下内容:

from application.app.folder.file import func_name

对此:

from .application.app.folder.file import func_name

通过添加点,您说的是在此文件夹中查找应用程序文件夹,而不是在Python目录中查找。

Your problem is that Python is looking in the Python directory for this file and not finding it. You must specify that you are talking about the directory that you are in and not the Python one.

To do this you change this:

from application.app.folder.file import func_name

to this:

from .application.app.folder.file import func_name

By adding the dot you are saying look in this folder for the application folder instead of looking in the Python directory.


回答 7

据我所知,__init__.py直接在要导入的函数的文件夹中添加一个文件即可完成此工作。

From what I know, add an __init__.py file directly in the folder of the functions you want to import will do the job.


回答 8

在Python 3.4和更高版本中,您可以直接从源文件导入(链接到文档)。这不是最简单的解决方案,但出于完整性考虑,我将其包括在内。

这是一个例子。首先,要导入的文件名为foo.py

def announce():
    print("Imported!")

在文档中的示例的大力启发下,导入上述文件的代码:

import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

foo = module_from_file("foo", "/path/to/foo.py")

if __name__ == "__main__":
    print(foo)
    print(dir(foo))
    foo.announce()

输出:

<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!

请注意,变量名称,模块名称和文件名不必匹配。该代码仍然有效:

import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

baz = module_from_file("bar", "/path/to/foo.py")

if __name__ == "__main__":
    print(baz)
    print(dir(baz))
    baz.announce()

输出:

<module 'bar' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!

Python 3.1中引入了以编程方式导入模块的功能,使您可以更好地控制模块的导入方式。有关更多信息,请参考文档。

In Python 3.4 and later, you can import from a source file directly (link to documentation). This is not the simplest solution, but I’m including this answer for completeness.

Here is an example. First, the file to be imported, named foo.py:

def announce():
    print("Imported!")

The code that imports the file above, inspired heavily by the example in the documentation:

import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

foo = module_from_file("foo", "/path/to/foo.py")

if __name__ == "__main__":
    print(foo)
    print(dir(foo))
    foo.announce()

The output:

<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!

Note that the variable name, the module name, and the filename need not match. This code still works:

import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

baz = module_from_file("bar", "/path/to/foo.py")

if __name__ == "__main__":
    print(baz)
    print(dir(baz))
    baz.announce()

The output:

<module 'bar' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!

Programmatically importing modules was introduced in Python 3.1 and gives you more control over how modules are imported. Refer to the documentation for more information.


回答 9

在Linux上的python3中为我工作

import sys  
sys.path.append(pathToFolderContainingScripts)  
from scriptName import functionName #scriptName without .py extension  

Worked for me in python3 on linux

import sys  
sys.path.append(pathToFolderContainingScripts)  
from scriptName import functionName #scriptName without .py extension  

回答 10

尝试使用Python的相对导入:

from ...app.folder.file import func_name

从当前目录开始,每个前导点都是层次结构中的另一个更高级别。


问题?如果这对您不起作用,那么您可能会被很多陷阱的相对进口所困扰。阅读答案和评论以获取更多详细信息: 即使使用__init__.py,也如何解决“尝试以非软件包方式进行相对导入”

提示:__init__.py在每个目录级别都有。您可能需要python -m application.app2.some_folder.some_file从顶层目录运行(或删除.py),或者在PYTHONPATH中具有该顶层目录。

Try Python’s relative imports:

from ...app.folder.file import func_name

Every leading dot is another higher level in the hierarchy beginning with the current directory.


Problems? If this isn’t working for you then you probably are getting bit by the many gotcha’s relative imports has. Read answers and comments for more details: How to fix “Attempted relative import in non-package” even with __init__.py

Hint: have __init__.py at every directory level. You might need python -m application.app2.some_folder.some_file (leaving off .py) which you run from the top level directory or have that top level directory in your PYTHONPATH. Phew!


回答 11

我面临着同样的挑战,尤其是在导入多个文件时,这就是我设法克服的方式。

import os, sys

from os.path import dirname, join, abspath
sys.path.insert(0, abspath(join(dirname(__file__), '..')))

from root_folder import file_name

I was faced with the same challenge, especially when importing multiple files, this is how I managed to overcome it.

import os, sys

from os.path import dirname, join, abspath
sys.path.insert(0, abspath(join(dirname(__file__), '..')))

from root_folder import file_name

回答 12

考虑到application作为根目录为你的Python项目,创建一个空__init__.py文件applicationappfolder文件夹。然后在您some_file.py进行如下更改以获取func_name的定义:

import sys
sys.path.insert(0, r'/from/root/directory/application')

from application.app.folder.file import func_name ## You can also use '*' wildcard to import all the functions in file.py file.
func_name()

Considering application as the root directory for your python project, create an empty __init__.py file in application, app and folder folders. Then in your some_file.py make changes as follows to get the definition of func_name:

import sys
sys.path.insert(0, r'/from/root/directory/application')

from application.app.folder.file import func_name ## You can also use '*' wildcard to import all the functions in file.py file.
func_name()

回答 13

将应用程序移至其他环境时,将sys.path.append与绝对路径一起使用并不理想。使用相对路径并不总是可行,因为当前工作目录取决于脚本的调用方式。

由于应用程序文件夹的结构是固定的,因此我们可以使用os.path来获取我们要导入的模块的完整路径。例如,如果这是结构:

/home/me/application/app2/some_folder/vanilla.py
/home/me/application/app2/another_folder/mango.py

假设您要导入“ mango”模块。您可以在vanilla.py中执行以下操作:

import sys, os.path
mango_dir = (os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
+ '/another_folder/')
sys.path.append(mango_dir)
import mango

当然,您不需要mango_dir变量。

要了解其工作原理,请看以下交互式会话示例:

>>> import os
>>> mydir = '/home/me/application/app2/some_folder'
>>> newdir = os.path.abspath(os.path.join(mydir, '..'))
>>> newdir
    '/home/me/application/app2'
>>> newdir = os.path.abspath(os.path.join(mydir, '..')) + '/another_folder'
>>> 
>>> newdir
'/home/me/application/app2/another_folder'
>>> 

并查看os.path文档。

Using sys.path.append with an absolute path is not ideal when moving the application to other environments. Using a relative path won’t always work because the current working directory depends on how the script was invoked.

Since the application folder structure is fixed, we can use os.path to get the full path of the module we wish to import. For example, if this is the structure:

/home/me/application/app2/some_folder/vanilla.py
/home/me/application/app2/another_folder/mango.py

And let’s say that you want to import the “mango” module. You could do the following in vanilla.py:

import sys, os.path
mango_dir = (os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
+ '/another_folder/')
sys.path.append(mango_dir)
import mango

Of course, you don’t need the mango_dir variable.

To understand how this works look at this interactive session example:

>>> import os
>>> mydir = '/home/me/application/app2/some_folder'
>>> newdir = os.path.abspath(os.path.join(mydir, '..'))
>>> newdir
    '/home/me/application/app2'
>>> newdir = os.path.abspath(os.path.join(mydir, '..')) + '/another_folder'
>>> 
>>> newdir
'/home/me/application/app2/another_folder'
>>> 

And check the os.path documentation.


回答 14

这对我在Windows上有效

# some_file.py on mainApp/app2 
import sys
sys.path.insert(0, sys.path[0]+'\\app2')

import some_file

This works for me on windows

# some_file.py on mainApp/app2 
import sys
sys.path.insert(0, sys.path[0]+'\\app2')

import some_file

回答 15

我很特别:我在Windows上使用Python!

我只需填写信息:对于Windows和Linux,相对路径和绝对路径都可以 sys.path(我需要相对路径,因为我在多台PC上和不同主目录下使用脚本)。

而且,当同时使用Windows \和Windows时,它们/都可以用作文件名的分隔符,当然,您必须加倍使用\Python字符串作为
一些有效示例:

sys.path.append('c:\\tools\\mydir')
sys.path.append('..\\mytools')
sys.path.append('c:/tools/mydir')
sys.path.append('../mytools')

(注意:如果它不是’Windows-native’的话,我认为它/\事件更方便,因为它与Linux兼容并且更容易编写和复制到Windows资源管理器中)

I’m quite special : I use Python with Windows !

I just complete information : for both Windows and Linux, both relative and absolute path work into sys.path (I need relative paths because I use my scripts on the several PCs and under different main directories).

And when using Windows both \ and / can be used as separator for file names and of course you must double \ into Python strings,
some valid examples :

sys.path.append('c:\\tools\\mydir')
sys.path.append('..\\mytools')
sys.path.append('c:/tools/mydir')
sys.path.append('../mytools')

(note : I think that / is more convenient than \, event if it is less ‘Windows-native’ because it is Linux-compatible and simpler to write and copy to Windows explorer)


回答 16

如果从特定路径加载模块的目的是在开发自定义模块的过程中为您提供帮助,则可以在测试脚本的同一文件夹中创建指向自定义模块根目录的符号链接。对于在该文件夹中运行的任何脚本,此模块引用将优先于安装的具有相同名称的任何其他模块。

我在Linux上进行了测试,但是它可以在任何支持符号链接的现代操作系统中使用。

这种方法的优点之一是,您可以指向位于您自己的本地SVC分支工作副本中的模块,这可以大大简化开发周期并减少管理模块不同版本的失败模式。

If the purpose of loading a module from a specific path is to assist you during the development of a custom module, you can create a symbolic link in the same folder of the test script that points to the root of the custom module. This module reference will take precedence over any other modules installed of the same name for any script run in that folder.

I tested this on Linux but it should work in any modern OS that supports symbolic links.

One advantage to this approach is that you can you can point to a module that’s sitting in your own local SVC branch working copy which can greatly simplify the development cycle time and reduce failure modes of managing different versions of the module.


回答 17

就我而言,我有一个要导入的类。我的文件如下所示:

# /opt/path/to/code/log_helper.py
class LogHelper:
    # stuff here

在我的主文件中,我通过以下方式包含了代码:

import sys
sys.path.append("/opt/path/to/code/")
from log_helper import LogHelper

In my case I had a class to import. My file looked like this:

# /opt/path/to/code/log_helper.py
class LogHelper:
    # stuff here

In my main file I included the code via:

import sys
sys.path.append("/opt/path/to/code/")
from log_helper import LogHelper

回答 18

我几次遇到相同的问题,所以我想分享我的解决方案。

Python版本:3.X

以下解决方案适用于使用Python 3.X版开发您的应用程序的人,因为自从Jan / 1/2020开始不支持Python 2

项目结构

在python 3中,__init__.py由于隐式命名空间包,您不需要在项目子目录中。见的init的.py不需要在Python包3.3+

Project 
├── main.py
├── .gitignore
|
├── a
|   └── file_a.py
|
└── b
    └── file_b.py

问题陈述

file_b.py,我想进口类Afile_a.py的文件夹下。

解决方案

#1快速但肮脏的方式

无需像您当前正在开发新项目那样安装软件包

使用try catch检查错误。代码示例:

import sys
try:
    # The insertion index should be 1 because index 0 is this file
    sys.path.insert(1, '/absolute/path/to/folder/a')  # the type of path is string
    # because the system path already have the absolute path to folder a
    # so it can recognize file_a.py while searching 
    from file_a import A
except (ModuleNotFoundError, ImportError) as e:
    print("{} fileure".format(type(e)))
else:
    print("Import succeeded")

#2安装软件包

一旦安装了应用程序(本文中不包含安装教程)

你可以简单地

try:
    from __future__ import absolute_import
    # now it can reach class A of file_a.py in folder a 
    # by relative import
    from ..a.file_a import A  
except (ModuleNotFoundError, ImportError) as e:
    print("{} fileure".format(type(e)))
else:
    print("Import succeeded")

编码愉快!

I bumped into the same question several times, so I would like to share my solution.

Python Version: 3.X

The following solution is for someone who develops your application in Python version 3.X because Python 2 is not supported since Jan/1/2020.

Project Structure

In python 3, you don’t need __init__.py in your project subdirectory due to the Implicit Namespace Packages. See Is init.py not required for packages in Python 3.3+

Project 
├── main.py
├── .gitignore
|
├── a
|   └── file_a.py
|
└── b
    └── file_b.py

Problem Statement

In file_b.py, I would like to import a class A in file_a.py under the folder a.

Solutions

#1 A quick but dirty way

Without installing the package like you are currently developing a new project

Using the try catch to check if the errors. Code example:

import sys
try:
    # The insertion index should be 1 because index 0 is this file
    sys.path.insert(1, '/absolute/path/to/folder/a')  # the type of path is string
    # because the system path already have the absolute path to folder a
    # so it can recognize file_a.py while searching 
    from file_a import A
except (ModuleNotFoundError, ImportError) as e:
    print("{} fileure".format(type(e)))
else:
    print("Import succeeded")

#2 Install your package

Once you installed your application (in this post, the tutorial of installation is not included)

You can simply

try:
    from __future__ import absolute_import
    # now it can reach class A of file_a.py in folder a 
    # by relative import
    from ..a.file_a import A  
except (ModuleNotFoundError, ImportError) as e:
    print("{} fileure".format(type(e)))
else:
    print("Import succeeded")

Happy coding!


回答 19

我正在研究a希望用户通过pip install a以下文件列表进行安装的项目:

.
├── setup.py
├── MANIFEST.in
└── a
    ├── __init__.py
    ├── a.py
    └── b
        ├── __init__.py
        └── b.py

setup.py

from setuptools import setup

setup (
  name='a',
  version='0.0.1',
  packages=['a'],
  package_data={
    'a': ['b/*'],
  },
)

清单

recursive-include b *.*

a / init .py

from __future__ import absolute_import

from a.a import cats
import a.b

a / a.py

cats = 0

a / b / init .py

from __future__ import absolute_import

from a.b.b import dogs

a / b / b.py

dogs = 1

我通过从目录运行以下命令来安装模块MANIFEST.in

python setup.py install

然后,从文件系统上一个完全不同的位置/moustache/armwrestle运行了:

import a
dir(a)

这证实了a.cats确实等于0且a.b.dogs确实等于1的意图。

I was working on project a that I wanted users to install via pip install a with the following file list:

.
├── setup.py
├── MANIFEST.in
└── a
    ├── __init__.py
    ├── a.py
    └── b
        ├── __init__.py
        └── b.py

setup.py

from setuptools import setup

setup (
  name='a',
  version='0.0.1',
  packages=['a'],
  package_data={
    'a': ['b/*'],
  },
)

MANIFEST.in

recursive-include b *.*

a/init.py

from __future__ import absolute_import

from a.a import cats
import a.b

a/a.py

cats = 0

a/b/init.py

from __future__ import absolute_import

from a.b.b import dogs

a/b/b.py

dogs = 1

I installed the module by running the following from the directory with MANIFEST.in:

python setup.py install

Then, from a totally different location on my filesystem /moustache/armwrestle I was able to run:

import a
dir(a)

Which confirmed that a.cats indeed equalled 0 and a.b.dogs indeed equalled 1, as intended.


回答 20

而不是只做一个import ...,这样做:

from <MySubFolder> import <MyFile>

MyFile在MySubFolder中。

Instead of just doing an import ..., do this :

from <MySubFolder> import <MyFile>

MyFile is inside the MySubFolder.


回答 21

您可以通过按f5刷新Python Shell,或转到“运行”->“运行模块”。这样,您无需更改目录即可从文件中读取内容。Python将自动更改目录。但是,如果您想使用Python Shell中不同目录中的不同文件,则可以像Cameron先前所说的那样在sys中更改目录。

You can refresh the Python shell by pressing f5, or go to Run-> Run Module. This way you don’t have to change the directory to read something from the file. Python will automatically change the directory. But if you want to work with different files from different directory in the Python Shell, then you can change the directory in sys, as Cameron said earlier.


回答 22

因此,我只是右键单击我的IDE,并添加了一个新的文件,folder并且想知道为什么我无法从中导入它。后来我意识到我必须右键单击并创建一个Python包,而不是经典的文件系统文件夹。或者在验尸方法中添加一个__init__.py(使python将文件系统文件夹视为一个包),如其他答案中所述。以防万一有人走这条路。

So I had just right clicked on my IDE, and added a new folder and was wondering why I wasn’t able to import from it. Later I realized I have to right click and create a Python Package, and not a classic file system folder. Or a post-mortem method being adding an __init__.py (which makes python treat the file system folder as a package) as mentioned in other answers. Adding this answer here just in case someone went this route.


回答 23

您可以使用importlib来导入模块,在该模块中,您可以使用如下所示的字符串从文件夹中导入模块:

import importlib

scriptName = 'Snake'

script = importlib.import_module('Scripts\\.%s' % scriptName)

这个示例有一个main.py,上面的代码是一个代码,然后是一个名为Scripts的文件夹,然后您可以通过更改scriptName变量从此文件夹中调用所需的任何内容。然后,您可以script用来引用该模块。例如,如果我Hello()在Snake模块中调用了一个函数,则可以通过以下方式运行此函数:

script.Hello()

我已经在Python 3.6中测试过

You can use importlib to import modules where you want to import a module from a folder using a string like so:

import importlib

scriptName = 'Snake'

script = importlib.import_module('Scripts\\.%s' % scriptName)

This example has a main.py which is the above code then a folder called Scripts and then you can call whatever you need from this folder by changing the scriptName variable. You can then use script to reference to this module. such as if I have a function called Hello() in the Snake module you can run this function by doing so:

script.Hello()

I have tested this in Python 3.6


回答 24

我已经遇到过这些问题很多次了。我经常来同一页。在上一个问题中,我必须server从固定目录运行,但是每次调试时,我都希望从不同的子目录运行。

import sys
sys.insert(1, /path) 

确实不是因为不同的模块,在为我工作,我不得不读不同*的.csv这都在同一个目录中的文件。

最后,我想对我有用的不是pythonic,而是:

在要调试的模块上使用了if __main__ 是从不同于通常的路径运行的。

所以:

# On top of the module, instead of on the bottom
import os
if __name__ == '__main__':
    os.chdir('/path/for/the/regularly/run/directory')

I’ve had these problems a number of times. I’ve come to this same page a lot. In my last problem I had to run the server from a fixed directory, but whenever debugging I wanted to run from different sub-directories.

import sys
sys.insert(1, /path) 

did NOT work for me because at different modules I had to read different *.csv files which were all in the same directory.

In the end, what worked for me was not pythonic, I guess, but:

I used a if __main__ on top of the module I wanted to debug, that is run from a different than usual path.

So:

# On top of the module, instead of on the bottom
import os
if __name__ == '__main__':
    os.chdir('/path/for/the/regularly/run/directory')