标签归档:python-import

ModuleNotFoundError:__main__不是软件包是什么意思?

问题:ModuleNotFoundError:__main__不是软件包是什么意思?

我正在尝试从控制台运行模块。我的目录结构是这样的:

我正在尝试使用以下命令p_03_using_bisection_search.pyproblem_set_02目录中运行模块:

$ python3 p_03_using_bisection_search.py

里面的代码p_03_using_bisection_search.py是:

__author__ = 'm'


from .p_02_paying_debt_off_in_a_year import compute_balance_after


def compute_bounds(balance: float,
                   annual_interest_rate: float) -> (float, float):

    # there is code here, but I have omitted it to save space
    pass


def compute_lowest_payment(balance: float,
                           annual_interest_rate: float) -> float:

    # there is code here, but I have omitted it to save space
    pass    

def main():
    balance = eval(input('Enter the initial balance: '))
    annual_interest_rate = eval(input('Enter the annual interest rate: '))

    lowest_payment = compute_lowest_payment(balance, annual_interest_rate)
    print('Lowest Payment: ' + str(lowest_payment))


if __name__ == '__main__':
    main()

我正在导入p_02_paying_debt_off_in_a_year.py其中代码是的函数:

__author__ = 'm'


def compute_balance(balance: float,
                    fixed_payment: float,
                    annual_interest_rate: float) -> float:

    # this is code that has been omitted
    pass


def compute_balance_after(balance: float,
                          fixed_payment: float,
                          annual_interest_rate: float,
                          months: int=12) -> float:

    # Omitted code
    pass


def compute_fixed_monthly_payment(balance: float,
                                  annual_interest_rate: float) -> float:

    # omitted code
    pass


def main():
    balance = eval(input('Enter the initial balance: '))
    annual_interest_rate = eval(
        input('Enter the annual interest rate as a decimal: '))
    lowest_payment = compute_fixed_monthly_payment(balance,
                                                   annual_interest_rate)
    print('Lowest Payment: ' + str(lowest_payment))


if __name__ == '__main__':
    main()

我收到以下错误:

ModuleNotFoundError: No module named '__main__.p_02_paying_debt_off_in_a_year'; '__main__' is not a package

我不知道如何解决这个问题。我尝试添加__init__.py文件,但是仍然无法正常工作。

I am trying to run a module from the console. The structure of my directory is this:

I am trying to run the module p_03_using_bisection_search.py, from the problem_set_02 directory using:

$ python3 p_03_using_bisection_search.py

The code inside p_03_using_bisection_search.pyis:

__author__ = 'm'


from .p_02_paying_debt_off_in_a_year import compute_balance_after


def compute_bounds(balance: float,
                   annual_interest_rate: float) -> (float, float):

    # there is code here, but I have omitted it to save space
    pass


def compute_lowest_payment(balance: float,
                           annual_interest_rate: float) -> float:

    # there is code here, but I have omitted it to save space
    pass    

def main():
    balance = eval(input('Enter the initial balance: '))
    annual_interest_rate = eval(input('Enter the annual interest rate: '))

    lowest_payment = compute_lowest_payment(balance, annual_interest_rate)
    print('Lowest Payment: ' + str(lowest_payment))


if __name__ == '__main__':
    main()

I am importing a function that is in p_02_paying_debt_off_in_a_year.py which code is:

__author__ = 'm'


def compute_balance(balance: float,
                    fixed_payment: float,
                    annual_interest_rate: float) -> float:

    # this is code that has been omitted
    pass


def compute_balance_after(balance: float,
                          fixed_payment: float,
                          annual_interest_rate: float,
                          months: int=12) -> float:

    # Omitted code
    pass


def compute_fixed_monthly_payment(balance: float,
                                  annual_interest_rate: float) -> float:

    # omitted code
    pass


def main():
    balance = eval(input('Enter the initial balance: '))
    annual_interest_rate = eval(
        input('Enter the annual interest rate as a decimal: '))
    lowest_payment = compute_fixed_monthly_payment(balance,
                                                   annual_interest_rate)
    print('Lowest Payment: ' + str(lowest_payment))


if __name__ == '__main__':
    main()

I am getting the following error:

ModuleNotFoundError: No module named '__main__.p_02_paying_debt_off_in_a_year'; '__main__' is not a package

I have no idea how to solve this issue. I have tried adding a __init__.py file, but it is still not working.


回答 0

只需删除相对导入的点,然后执行以下操作:

from p_02_paying_debt_off_in_a_year import compute_balance_after

Simply remove the dot for the relative import and do:

from p_02_paying_debt_off_in_a_year import compute_balance_after

回答 1

我和你有同样的问题。我认为问题是您在中使用了相对导入in-package import__init__.py您的目录中没有。因此,请按照以上摩西的回答进行导入。

我认为核心问题是在导入点时:

from .p_02_paying_debt_off_in_a_year import compute_balance_after

它等效于:

from __main__.p_02_paying_debt_off_in_a_year import compute_balance_after

where __main__指您当前的模块p_03_using_bisection_search.py


简而言之,解释器不知道您的目录体系结构。

当解释器进入时p_03.py,脚本等于:

from p_03_using_bisection_search.p_02_paying_debt_off_in_a_year import compute_balance_after

并且p_03_using_bisection_search不包含任何名为的模块或实例p_02_paying_debt_off_in_a_year


因此,我想出了一个更干净的解决方案,而无需更改python环境的贵重物品(在查找请求在相对导入中的作用之后):

该目录的主要体系结构是:

main.py

setup.py

problem_set_02/

——__init__.py

——p01.py

——p02.py

——p03.py

然后写__init__.py

from .p_02_paying_debt_off_in_a_year import compute_balance_after

这里__main____init__,它究竟指的是模块problem_set_02

然后转到main.py

import problem_set_02

您也可以编写一个setup.py将特定模块添加到环境中。

I have the same issue as you did. I think the problem is that you used relative import in in-package import. There is no __init__.py in your directory. So just import as Moses answered above.

The core issue I think is when you import with a dot:

from .p_02_paying_debt_off_in_a_year import compute_balance_after

It is equivalent to:

from __main__.p_02_paying_debt_off_in_a_year import compute_balance_after

where __main__ refers to your current module p_03_using_bisection_search.py.


Briefly, the interpreter does not know your directory architecture.

When the interpreter get in p_03.py, the script equals:

from p_03_using_bisection_search.p_02_paying_debt_off_in_a_year import compute_balance_after

and p_03_using_bisection_search does not contain any modules or instances called p_02_paying_debt_off_in_a_year.


So I came up with a cleaner solution without changing python environment valuables (after looking up how requests do in relative import):

The main architecture of the directory is:

main.py
setup.py
problem_set_02/
   __init__.py
   p01.py
   p02.py
   p03.py

Then write in __init__.py:

from .p_02_paying_debt_off_in_a_year import compute_balance_after

Here __main__ is __init__ , it exactly refers to the module problem_set_02.

Then go to main.py:

import problem_set_02

You can also write a setup.py to add specific module to the environment.


回答 2

尝试将其运行为:

python3 -m p_03_using_bisection_search

Try to run it as:

python3 -m p_03_using_bisection_search


回答 3

您好,请按照以下步骤操作,您将解决此问题。如果已创建目录和子目录,请按照以下步骤操作,请记住,所有目录必须必须 __init__.py将其识别为目录。

  1. import sys并运行sys.path,您将能够看到python搜索的所有路径。您必须能够看到当前的工作目录。

  2. 现在,按照以下命令导入要使用import使用的子目录和相应模块:import subdir.subdir.modulename as abc现在,您可以使用该模块中的方法。 屏幕截图相同的问题

如您在此屏幕快照中看到的,我有一个父目录和两个子目录,在第二个子目录下,我有module == CommonFunction,执行sys.path后您会看到右侧,我可以看到我的工作目录

If you have created directory and sub-directory, follow the steps below and please keep in mind all directory must have __init__.py to get it recognized as a directory.

  1. In your script, include import sys and sys.path, you will be able to see all the paths available to Python. You must be able to see your current working directory.

  2. Now import sub-directory and respective module that you want to use using: import subdir.subdir.modulename as abc and now you can use the methods in that module.

As an example, you can see in this screenshot I have one parent directory and two sub-directories and under second sub-directories I have the module CommonFunction. On the right my console shows that after execution of sys.path, I can see my working directory.


回答 4

删除点并在文件开头导入absolute_import

from __future__ import absolute_import

from p_02_paying_debt_off_in_a_year import compute_balance_after

Remove the dot and import absolute_import in the beginning of your file

from __future__ import absolute_import

from p_02_paying_debt_off_in_a_year import compute_balance_after

回答 5

只需使用.py文件所在的主文件夹的名称即可。

from problem_set_02.p_02_paying_debt_off_in_a_year import compute_balance_after

Just use the name of the main folder which the .py file is in.

from problem_set_02.p_02_paying_debt_off_in_a_year import compute_balance_after

兄弟包进口

问题:兄弟包进口

我已经尝试阅读有关同级导入甚至 包文档的问题,但是我还没有找到答案。

具有以下结构:

├── LICENSE.md
├── README.md
├── api
   ├── __init__.py
   ├── api.py
   └── api_key.py
├── examples
   ├── __init__.py
   ├── example_one.py
   └── example_two.py
└── tests
   ├── __init__.py
   └── test_one.py

examplestests目录中的脚本如何 从api模块导入 并从命令行运行?

另外,我想避免sys.path.insert对每个文件进行难看的修改。当然可以在Python中完成,对吗?

I’ve tried reading through questions about sibling imports and even the package documentation, but I’ve yet to find an answer.

With the following structure:

├── LICENSE.md
├── README.md
├── api
│   ├── __init__.py
│   ├── api.py
│   └── api_key.py
├── examples
│   ├── __init__.py
│   ├── example_one.py
│   └── example_two.py
└── tests
│   ├── __init__.py
│   └── test_one.py

How can the scripts in the examples and tests directories import from the api module and be run from the commandline?

Also, I’d like to avoid the ugly sys.path.insert hack for every file. Surely this can be done in Python, right?


回答 0

七年后

自从我在下面写下答案以来,修改sys.path仍然是一种快速技巧,对于私有脚本来说效果很好,但是已经有了一些改进

  • 安装该软件包(无论是否在virtualenv中)都将为您提供所需的内容,尽管我建议使用pip进行操作,而不是直接使用setuptools(并setup.cfg用于存储元数据)
  • 使用该-m标志并作为软件包运行也可以(但是如果要将工作目录转换为可安装的软件包,将会有些尴尬)。
  • 对于测试,特别是pytest能够在这种情况下找到api程序包,并sys.path为您解决问题

因此,这实际上取决于您要做什么。但是,就您而言,既然您的目标似乎是在某个时候制作一个合适的程序包,那么通过安装pip -e可能是您最好的选择,即使它尚不完美。

旧答案

正如其他地方已经说过的那样,可怕的事实是,您必须进行丑陋的修改才能允许从同级模块中导入数据或从该__main__模块中的父级程序包中进行导入。PEP 366中详细介绍了该问题。PEP 3122试图以更合理的方式处理进口,但圭多拒绝了它的一项

唯一的用例似乎是正在运行的脚本,它们恰好位于模块的目录中,我一直将其视为反模式。

这里

不过,我会定期使用这种模式

# Ugly hack to allow absolute import from the root folder
# whatever its name is. Please forgive the heresy.
if __name__ == "__main__" and __package__ is None:
    from sys import path
    from os.path import dirname as dir

    path.append(dir(path[0]))
    __package__ = "examples"

import api

path[0]是运行脚本的父文件夹和dir(path[0])顶级文件夹。

虽然我仍然不能使用相对导入,但是它确实允许从顶层(在您的示例api的父文件夹中)进行绝对导入。

Seven years after

Since I wrote the answer below, modifying sys.path is still a quick-and-dirty trick that works well for private scripts, but there has been several improvements

  • Installing the package (in a virtualenv or not) will give you what you want, though I would suggest using pip to do it rather than using setuptools directly (and using setup.cfg to store the metadata)
  • Using the -m flag and running as a package works too (but will turn out a bit awkward if you want to convert your working directory into an installable package).
  • For the tests, specifically, pytest is able to find the api package in this situation and takes care of the sys.path hacks for you

So it really depends on what you want to do. In your case, though, since it seems that your goal is to make a proper package at some point, installing through pip -e is probably your best bet, even if it is not perfect yet.

Old answer

As already stated elsewhere, the awful truth is that you have to do ugly hacks to allow imports from siblings modules or parents package from a __main__ module. The issue is detailed in PEP 366. PEP 3122 attempted to handle imports in a more rational way but Guido has rejected it one the account of

The only use case seems to be running scripts that happen to be living inside a module’s directory, which I’ve always seen as an antipattern.

(here)

Though, I use this pattern on a regular basis with

# Ugly hack to allow absolute import from the root folder
# whatever its name is. Please forgive the heresy.
if __name__ == "__main__" and __package__ is None:
    from sys import path
    from os.path import dirname as dir

    path.append(dir(path[0]))
    __package__ = "examples"

import api

Here path[0] is your running script’s parent folder and dir(path[0]) your top level folder.

I have still not been able to use relative imports with this, though, but it does allow absolute imports from the top level (in your example api‘s parent folder).


回答 1

厌倦了sys.path hacks?

有大量的sys.path.append-hacks,但是我找到了另一种解决问题的方法。

摘要

  • 将代码包装到一个文件夹中(例如packaged_stuff
  • setup.py在使用setuptools.setup()的地方使用创建脚本。
  • 使用以下命令以可编辑状态安装软件包 pip install -e <myproject_folder>
  • 导入使用 from packaged_stuff.modulename import function_name

建立

起点是您提供的文件结构,包装在名为的文件夹中myproject

.
└── myproject
    ├── api
       ├── api_key.py
       ├── api.py
       └── __init__.py
    ├── examples
       ├── example_one.py
       ├── example_two.py
       └── __init__.py
    ├── LICENCE.md
    ├── README.md
    └── tests
        ├── __init__.py
        └── test_one.py

我将调用.根文件夹,在本例中,它位于C:\tmp\test_imports\

api.py

作为测试用例,让我们使用以下./api/api.py

def function_from_api():
    return 'I am the return value from api.api!'

test_one.py

from api.api import function_from_api

def test_function():
    print(function_from_api())

if __name__ == '__main__':
    test_function()

尝试运行test_one:

PS C:\tmp\test_imports> python .\myproject\tests\test_one.py
Traceback (most recent call last):
  File ".\myproject\tests\test_one.py", line 1, in <module>
    from api.api import function_from_api
ModuleNotFoundError: No module named 'api'

还尝试相对进口将无法正常工作:

使用from ..api.api import function_from_api会导致

PS C:\tmp\test_imports> python .\myproject\tests\test_one.py
Traceback (most recent call last):
  File ".\tests\test_one.py", line 1, in <module>
    from ..api.api import function_from_api
ValueError: attempted relative import beyond top-level package

脚步

  1. 将setup.py文件创建到根目录

的内容为setup.py*

from setuptools import setup, find_packages

setup(name='myproject', version='1.0', packages=find_packages())
  1. 使用虚拟环境

如果您熟悉虚拟环境,请激活一个,然后跳到下一步。虚拟环境的使用不是绝对必需的,但从长远来看(当您正在进行多个项目时),它们确实可以帮助您。最基本的步骤是(在根文件夹中运行)

  • 创建虚拟环境
    • python -m venv venv
  • 激活虚拟环境
    • source ./venv/bin/activate(Linux,macOS)或./venv/Scripts/activate(Win)

要了解更多信息,只需在Google上搜索“ python虚拟环境教程”或类似内容即可。除了创建,激活和停用之外,您可能根本不需要任何其他命令。

创建并激活虚拟环境后,控制台应在括号中提供虚拟环境的名称。

PS C:\tmp\test_imports> python -m venv venv
PS C:\tmp\test_imports> .\venv\Scripts\activate
(venv) PS C:\tmp\test_imports>

您的文件夹树应如下所示**

.
├── myproject
   ├── api
      ├── api_key.py
      ├── api.py
      └── __init__.py
   ├── examples
      ├── example_one.py
      ├── example_two.py
      └── __init__.py
   ├── LICENCE.md
   ├── README.md
   └── tests
       ├── __init__.py
       └── test_one.py
├── setup.py
└── venv
    ├── Include
    ├── Lib
    ├── pyvenv.cfg
    └── Scripts [87 entries exceeds filelimit, not opening dir]
  1. pip以可编辑状态安装项目

安装您的顶级包myproject使用pip。诀窍是-e在执行安装时使用标志。这样,它以可编辑状态安装,并且对.py文件所做的所有编辑将自动包含在已安装的软件包中。

在根目录中,运行

pip install -e . (注意点,它代表“当前目录”)

您还可以看到它是通过使用安装的 pip freeze

(venv) PS C:\tmp\test_imports> pip install -e .
Obtaining file:///C:/tmp/test_imports
Installing collected packages: myproject
  Running setup.py develop for myproject
Successfully installed myproject
(venv) PS C:\tmp\test_imports> pip freeze
myproject==1.0
  1. 添加myproject.到您的进口中

请注意,您将只需要添加myproject.导入否则将无法正常工作。不能使用setup.py&导入的导入pip install仍然可以正常工作。请参见下面的示例。


测试解决方案

现在,让我们使用api.py上面test_one.py定义的和下面定义的测试解决方案。

test_one.py

from myproject.api.api import function_from_api

def test_function():
    print(function_from_api())

if __name__ == '__main__':
    test_function()

运行测试

(venv) PS C:\tmp\test_imports> python .\myproject\tests\test_one.py
I am the return value from api.api!

*有关更多详细的setup.py示例,请参阅setuptools文档

**实际上,您可以将虚拟环境放在硬盘上的任何位置。

Tired of sys.path hacks?

There are plenty of sys.path.append -hacks available, but I found an alternative way of solving the problem in hand.

Summary

  • Wrap the code into one folder (e.g. packaged_stuff)
  • Use create setup.py script where you use setuptools.setup().
  • Pip install the package in editable state with pip install -e <myproject_folder>
  • Import using from packaged_stuff.modulename import function_name

Setup

The starting point is the file structure you have provided, wrapped in a folder called myproject.

.
└── myproject
    ├── api
    │   ├── api_key.py
    │   ├── api.py
    │   └── __init__.py
    ├── examples
    │   ├── example_one.py
    │   ├── example_two.py
    │   └── __init__.py
    ├── LICENCE.md
    ├── README.md
    └── tests
        ├── __init__.py
        └── test_one.py

I will call the . the root folder, and in my example case it is located at C:\tmp\test_imports\.

api.py

As a test case, let’s use the following ./api/api.py

def function_from_api():
    return 'I am the return value from api.api!'

test_one.py

from api.api import function_from_api

def test_function():
    print(function_from_api())

if __name__ == '__main__':
    test_function()

Try to run test_one:

PS C:\tmp\test_imports> python .\myproject\tests\test_one.py
Traceback (most recent call last):
  File ".\myproject\tests\test_one.py", line 1, in <module>
    from api.api import function_from_api
ModuleNotFoundError: No module named 'api'

Also trying relative imports wont work:

Using from ..api.api import function_from_api would result into

PS C:\tmp\test_imports> python .\myproject\tests\test_one.py
Traceback (most recent call last):
  File ".\tests\test_one.py", line 1, in <module>
    from ..api.api import function_from_api
ValueError: attempted relative import beyond top-level package

Steps

  1. Make a setup.py file to the root level directory

The contents for the setup.py would be*

from setuptools import setup, find_packages

setup(name='myproject', version='1.0', packages=find_packages())
  1. Use a virtual environment

If you are familiar with virtual environments, activate one, and skip to the next step. Usage of virtual environments are not absolutely required, but they will really help you out in the long run (when you have more than 1 project ongoing..). The most basic steps are (run in the root folder)

  • Create virtual env
    • python -m venv venv
  • Activate virtual env
    • source ./venv/bin/activate (Linux, macOS) or ./venv/Scripts/activate (Win)

To learn more about this, just Google out “python virtual env tutorial” or similar. You probably never need any other commands than creating, activating and deactivating.

Once you have made and activated a virtual environment, your console should give the name of the virtual environment in parenthesis

PS C:\tmp\test_imports> python -m venv venv
PS C:\tmp\test_imports> .\venv\Scripts\activate
(venv) PS C:\tmp\test_imports>

and your folder tree should look like this**

.
├── myproject
│   ├── api
│   │   ├── api_key.py
│   │   ├── api.py
│   │   └── __init__.py
│   ├── examples
│   │   ├── example_one.py
│   │   ├── example_two.py
│   │   └── __init__.py
│   ├── LICENCE.md
│   ├── README.md
│   └── tests
│       ├── __init__.py
│       └── test_one.py
├── setup.py
└── venv
    ├── Include
    ├── Lib
    ├── pyvenv.cfg
    └── Scripts [87 entries exceeds filelimit, not opening dir]
  1. pip install your project in editable state

Install your top level package myproject using pip. The trick is to use the -e flag when doing the install. This way it is installed in an editable state, and all the edits made to the .py files will be automatically included in the installed package.

In the root directory, run

pip install -e . (note the dot, it stands for “current directory”)

You can also see that it is installed by using pip freeze

(venv) PS C:\tmp\test_imports> pip install -e .
Obtaining file:///C:/tmp/test_imports
Installing collected packages: myproject
  Running setup.py develop for myproject
Successfully installed myproject
(venv) PS C:\tmp\test_imports> pip freeze
myproject==1.0
  1. Add myproject. into your imports

Note that you will have to add myproject. only into imports that would not work otherwise. Imports that worked without the setup.py & pip install will work still work fine. See an example below.


Test the solution

Now, let’s test the solution using api.py defined above, and test_one.py defined below.

test_one.py

from myproject.api.api import function_from_api

def test_function():
    print(function_from_api())

if __name__ == '__main__':
    test_function()

running the test

(venv) PS C:\tmp\test_imports> python .\myproject\tests\test_one.py
I am the return value from api.api!

* See the setuptools docs for more verbose setup.py examples.

** In reality, you could put your virtual environment anywhere on your hard disk.


回答 2

这是我在文件tests夹中的Python文件顶部插入的另一种选择:

# Path hack.
import sys, os
sys.path.insert(0, os.path.abspath('..'))

Here is another alternative that I insert at top of the Python files in tests folder:

# Path hack.
import sys, os
sys.path.insert(0, os.path.abspath('..'))

回答 3

sys.path除非有必要,否则您不需要,也不应hack ,在这种情况下则没有必要。用:

import api.api_key # in tests, examples

从项目目录运行:python -m tests.test_one

您可能应该tests在内部移动(如果它们是api的unittests)api并运行python -m api.test以运行所有测试(假设存在__main__.py)或python -m api.test.test_one改为运行test_one

您也可以__init__.pyexamples(不是Python软件包)中删除该示例,并在api安装了virtualenv的示例中运行示例,例如,如果您具有适当的条件,则pip install -e .在virtualenv中将安装就地api软件包setup.py

You don’t need and shouldn’t hack sys.path unless it is necessary and in this case it is not. Use:

import api.api_key # in tests, examples

Run from the project directory: python -m tests.test_one.

You should probably move tests (if they are api’s unittests) inside api and run python -m api.test to run all tests (assuming there is __main__.py) or python -m api.test.test_one to run test_one instead.

You could also remove __init__.py from examples (it is not a Python package) and run the examples in a virtualenv where api is installed e.g., pip install -e . in a virtualenv would install inplace api package if you have proper setup.py.


回答 4

我还没有对Python的理解,没有看到在没有同级/相对导入hack的情况下在不相关的项目之间共享代码的预期方式所必需的。直到那天,这是我的解决方案。对于examplestests从中导入东西..\api,它看起来像:

import sys.path
import os.path
# Import from sibling directory ..\api
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/..")
import api.api
import api.api_key

I don’t yet have the comprehension of Pythonology necessary to see the intended way of sharing code amongst unrelated projects without a sibling/relative import hack. Until that day, this is my solution. For examples or tests to import stuff from ..\api, it would look like:

import sys.path
import os.path
# Import from sibling directory ..\api
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/..")
import api.api
import api.api_key

回答 5

对于同级包导入,可以使用[sys.path] [2]模块的insertappend方法:

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

如果您按以下方式启动脚本,这将起作用:

python examples/example_one.py
python tests/test_one.py

另一方面,您也可以使用相对导入:

if __name__ == '__main__' and if __package__ is not None:
    import ..api.api

在这种情况下,您将必须使用‘-m’参数启动脚本(请注意,在这种情况下,您不得使用‘.py’扩展名):

python -m packageName.examples.example_one
python -m packageName.tests.test_one

当然,您可以将两种方法混合使用,以便您的脚本无论如何调用都可以工作:

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

For siblings package imports, you can use either the insert or the append method of the [sys.path][2] module:

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

This will work if you are launching your scripts as follows:

python examples/example_one.py
python tests/test_one.py

On the other hand, you can also use the relative import:

if __name__ == '__main__' and if __package__ is not None:
    import ..api.api

In this case you will have to launch your script with the ‘-m’ argument (note that, in this case, you must not give the ‘.py’ extension):

python -m packageName.examples.example_one
python -m packageName.tests.test_one

Of course, you can mix the two approaches, so that your script will work no matter how it is called:

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

回答 6

TLDR

此方法不需要setuptools,path hacks,其他命令行参数或在项目的每个文件中指定软件包的顶层。

只需在要调用的父目录中创建一个脚本,__main__然后从那里运行所有内容即可。有关进一步的说明,请继续阅读。

说明

这可以实现,而无需一起寻找新路径,使用额外的命令行参数或向您的每个程序添加代码以识别其兄弟姐妹。

我相信之前提到的失败的原因是被调用的程序将其__name__设置为__main__。发生这种情况时,被调用的脚本会接受自身位于程序包的顶层,并拒绝识别兄弟目录中的脚本。

但是,目录顶层下的所有内容仍然可以识别顶层下的任何内容。这意味着要使同级目录中的文件相互识别/利用,您只需要做的就是从其父目录中的脚本中调用它们。

概念证明 在具有以下结构的目录中:

.
|__Main.py
|
|__Siblings
   |
   |___sib1
   |   |
   |   |__call.py
   |
   |___sib2
       |
       |__callsib.py

Main.py 包含以下代码:

import sib1.call as call


def main():
    call.Call()


if __name__ == '__main__':
    main()

sib1 / call.py包含:

import sib2.callsib as callsib


def Call():
    callsib.CallSib()


if __name__ == '__main__':
    Call()

sib2 / callsib.py包含:

def CallSib():
    print("Got Called")

if __name__ == '__main__':
    CallSib()

如果重现此示例,您将注意到, 即使通过Main.py调用,调用也会导致按定义打印“ Got Called” 。但是,如果要直接调用(在对导入进行适当更改之后),则会引发异常。即使它由其父目录中的脚本调用时可以工作,但是如果它认为自己位于程序包的顶层,则它将无法工作。sib2/callsib.pysib2/callsib.pysib1/call.pysib1/call.py

TLDR

This method does not require setuptools, path hacks, additional command line arguments, or specifying the top level of the package in every single file of your project.

Just make a script in the parent directory of whatever your are calling to be your __main__ and run everything from there. For further explanation continue reading.

Explanation

This can be accomplished without hacking a new path together, extra command line args, or adding code to each of your programs to recognize its siblings.

The reason this fails as I believe was mentioned before is the programs being called have their __name__ set as __main__. When this occurs the script being called accepts itself to be on the top level of the package and refuses to recognize scripts in sibling directories.

However, everything under the top level of the directory will still recognize ANYTHING ELSE under the top level. This means the ONLY thing you have to do to get files in sibling directories to recognize/utilize each other is to call them from a script in their parent directory.

Proof of Concept In a dir with the following structure:

.
|__Main.py
|
|__Siblings
   |
   |___sib1
   |   |
   |   |__call.py
   |
   |___sib2
       |
       |__callsib.py

Main.py contains the following code:

import sib1.call as call


def main():
    call.Call()


if __name__ == '__main__':
    main()

sib1/call.py contains:

import sib2.callsib as callsib


def Call():
    callsib.CallSib()


if __name__ == '__main__':
    Call()

and sib2/callsib.py contains:

def CallSib():
    print("Got Called")

if __name__ == '__main__':
    CallSib()

If you reproduce this example you will notice that calling Main.py will result in “Got Called” being printed as is defined in sib2/callsib.py even though sib2/callsib.py got called through sib1/call.py. However if one were to directly call sib1/call.py (after making appropriate changes to the imports) it throws an exception. Even though it worked when called by the script in its parent directory, it will not work if it believes itself to be on the top level of the package.


回答 7

我制作了一个示例项目来演示如何处理此问题,这确实是如上所述的另一个sys.path hack。Python Sibling Import Example,它依赖于:

if __name__ == '__main__': import os import sys sys.path.append(os.getcwd())

只要您的工作目录位于Python项目的根目录下,这似乎就非常有效。如果有人将其部署在实际的生产环境中,那么很高兴听到它是否也可以在此环境中工作。

I made a sample project to demonstrate how I handled this, which is indeed another sys.path hack as indicated above. Python Sibling Import Example, which relies on:

if __name__ == '__main__': import os import sys sys.path.append(os.getcwd())

This seems to be pretty effective so long as your working directory remains at the root of the Python project. If anyone deploys this in a real production environment it’d be great to hear if it works there as well.


回答 8

您需要查看如何在相关代码中编写导入语句。如果examples/example_one.py使用以下导入语句:

import api.api

…然后,它希望项目的根目录位于系统路径中。

最简单的方法来支持此操作(如您所说),就是从顶层目录运行示例,如下所示:

PYTHONPATH=$PYTHONPATH:. python examples/example_one.py 

You need to look to see how the import statements are written in the related code. If examples/example_one.py uses the following import statement:

import api.api

…then it expects the root directory of the project to be in the system path.

The easiest way to support this without any hacks (as you put it) would be to run the examples from the top level directory, like this:

PYTHONPATH=$PYTHONPATH:. python examples/example_one.py 

回答 9

以防万一有人在Eclipse上使用Pydev的情况出现在这里:您可以使用Project-> Properties并在左侧菜单Pydev-PYTHONPATH下设置External Libraries,将同级的父路径(以及调用模块的父路径)添加为外部库文件夹。然后,您可以从同级导入,例如。from sibling import some_class

Just in case someone using Pydev on Eclipse end up here: you can add the sibling’s parent path (and thus the calling module’s parent) as an external library folder using Project->Properties and setting External Libraries under the left menu Pydev-PYTHONPATH. Then you can import from your sibling, e. g. from sibling import some_class.


回答 10

首先,应避免使用与模块本身同名的文件。它可能会破坏其他进口。

导入文件时,首先解释器检查当前目录,然后搜索全局目录。

里面examples或者tests您可以拨打:

from ..api import api

First, you should avoid having files with the same name as the module itself. It may break other imports.

When you import a file, first the interpreter checks the current directory and then searchs global directories.

Inside examples or tests you can call:

from ..api import api

如何在不导入的情况下检查python模块是否存在

问题:如何在不导入的情况下检查python模块是否存在

我需要知道是否存在python模块,而不导入它。

导入可能不存在的内容(不是我想要的):

try:
    import eggs
except ImportError:
    pass

I need to know if a python module exists, without importing it.

Importing something that might not exist (not what I want):

try:
    import eggs
except ImportError:
    pass

回答 0

Python2

要检查导入是否可以在python2中找到某些内容,请使用 imp

import imp
try:
    imp.find_module('eggs')
    found = True
except ImportError:
    found = False

要查找点状导入,您需要执行以下操作:

import imp
try:
    spam_info = imp.find_module('spam')
    spam = imp.load_module('spam', *spam_info)
    imp.find_module('eggs', spam.__path__) # __path__ is already a list
    found = True
except ImportError:
    found = False

您还可以使用pkgutil.find_loader(与python3部分大致相同

import pkgutil
eggs_loader = pkgutil.find_loader('eggs')
found = eggs_loader is not None

Python3

Python3≤3.3

您应该使用importlib,我如何做到这一点是:

import importlib
spam_loader = importlib.find_loader('spam')
found = spam_loader is not None

我的期望是,如果您可以找到它的装载机,那么它存在。您也可以对此稍加精明,例如过滤掉您将接受的装载程序。例如:

import importlib
spam_loader = importlib.find_loader('spam')
# only accept it as valid if there is a source file for the module - no bytecode only.
found = issubclass(type(spam_loader), importlib.machinery.SourceFileLoader)

Python3≥3.4

在Python3.4中,不推荐使用importlib.find_loader python文档,而推荐使用importlib.util.find_spec。推荐的方法是importlib.util.find_spec。还有其他类似的东西importlib.machinery.FileFinder,如果您要加载特定的文件,则很有用。弄清楚如何使用它们超出了此范围。

import importlib
spam_spec = importlib.util.find_spec("spam")
found = spam_spec is not None

这也适用于相对进口,但您必须提供起始包装,因此您也可以这样做:

import importlib
spam_spec = importlib.util.find_spec("..spam", package="eggs.bar")
found = spam_spec is not None
spam_spec.name == "eggs.spam"

虽然我确定这样做是有原因的-我不确定会是什么。

警告

尝试查找子模块时,它将导入父模块(适用于上述所有方法)!

food/
  |- __init__.py
  |- eggs.py

## __init__.py
print("module food loaded")

## eggs.py
print("module eggs")

were you then to run
>>> import importlib
>>> spam_spec = importlib.find_spec("food.eggs")
module food loaded
ModuleSpec(name='food.eggs', loader=<_frozen_importlib.SourceFileLoader object at 0x10221df28>, origin='/home/user/food/eggs.py')

欢迎对此发表评论

致谢

  • @rvighne用于importlib
  • @ lucas-guido用于python3.3 +的描述 find_loader
  • @enpenax用于python2.7中的pkgutils.find_loader行为

Python2

To check if import can find something in python2, using imp

import imp
try:
    imp.find_module('eggs')
    found = True
except ImportError:
    found = False

To find dotted imports, you need to do more:

import imp
try:
    spam_info = imp.find_module('spam')
    spam = imp.load_module('spam', *spam_info)
    imp.find_module('eggs', spam.__path__) # __path__ is already a list
    found = True
except ImportError:
    found = False

You can also use pkgutil.find_loader (more or less the same as the python3 part

import pkgutil
eggs_loader = pkgutil.find_loader('eggs')
found = eggs_loader is not None

Python3

Python3 ≤ 3.3

You should use importlib, How I went about doing this was:

import importlib
spam_loader = importlib.find_loader('spam')
found = spam_loader is not None

My expectation being, if you can find a loader for it, then it exists. You can also be a bit more smart about it, like filtering out what loaders you will accept. For example:

import importlib
spam_loader = importlib.find_loader('spam')
# only accept it as valid if there is a source file for the module - no bytecode only.
found = issubclass(type(spam_loader), importlib.machinery.SourceFileLoader)

Python3 ≥ 3.4

In Python3.4 importlib.find_loader python docs was deprecated in favour of importlib.util.find_spec. The recommended method is the importlib.util.find_spec. There are others like importlib.machinery.FileFinder, which is useful if you’re after a specific file to load. Figuring out how to use them is beyond the scope of this.

import importlib
spam_spec = importlib.util.find_spec("spam")
found = spam_spec is not None

This also works with relative imports but you must supply the starting package, so you could also do:

import importlib
spam_spec = importlib.util.find_spec("..spam", package="eggs.bar")
found = spam_spec is not None
spam_spec.name == "eggs.spam"

While I’m sure there exists a reason for doing this – I’m not sure what it would be.

WARNING

When trying to find a submodule, it will import the parent module (for all of the above methods)!

food/
  |- __init__.py
  |- eggs.py

## __init__.py
print("module food loaded")

## eggs.py
print("module eggs")

were you then to run
>>> import importlib
>>> spam_spec = importlib.find_spec("food.eggs")
module food loaded
ModuleSpec(name='food.eggs', loader=<_frozen_importlib.SourceFileLoader object at 0x10221df28>, origin='/home/user/food/eggs.py')

comments welcome on getting around this

Acknowledgements

  • @rvighne for importlib
  • @lucas-guido for python3.3+ depricating find_loader
  • @enpenax for pkgutils.find_loader behaviour in python2.7

回答 1

Python 3> = 3.6:ModuleNotFoundError

ModuleNotFoundError在已经出台的Python 3.6,并且可以用于此目的

try:
    import eggs
except ModuleNotFoundError:
    # Error handling
    pass

如果找不到模块或其父级之一,则会引发该错误。所以

try:
    import eggs.sub
except ModuleNotFoundError as err:
    # Error handling
    print(err)

会显示一条消息,看起来像找不到No module named 'eggs'eggs模块;但将打印出类似这样No module named 'eggs.sub'如果只有sub模块无法找到,但eggs包可能被发现。

有关更多信息,请参见导入系统文档。ModuleNotFoundError

Python 3 >= 3.6: ModuleNotFoundError

The ModuleNotFoundError has been introduced in python 3.6 and can be used for this purpose

try:
    import eggs
except ModuleNotFoundError:
    # Error handling
    pass

The error is raised when a module or one of its parents cannot be found. So

try:
    import eggs.sub
except ModuleNotFoundError as err:
    # Error handling
    print(err)

would print a message that looks like No module named 'eggs' if the eggs module cannot be found; but would print something like No module named 'eggs.sub' if only the sub module couldn’t be found but the eggs package could be found.

See the documentation of the import system for more info on the ModuleNotFoundError


回答 2

在使用yarbelk的响应后,我做了这个,因为不必import ìmp

try:
    __import__('imp').find_module('eggs')
    # Make things with supposed existing module
except ImportError:
    pass

settings.py例如在Django中很有用。

After use yarbelk’s response, I’ve made this for don’t have to import ìmp.

try:
    __import__('imp').find_module('eggs')
    # Make things with supposed existing module
except ImportError:
    pass

Useful in Django’s settings.pyfor example.


回答 3

Python 2,无需依赖ImportError

在更新当前答案之前,这是Python 2的方法

import pkgutil
import importlib

if pkgutil.find_loader(mod) is not None:
    return importlib.import_module(mod)
return None

为什么还要另一个答案?

很多答案都抓住了答案ImportError。问题在于,我们不知道是什么引发了ImportError

如果导入现有模块,而模块中恰好有一个ImportError(例如第1行的错字),则结果将是您的模块不存在。您将需要大量回溯才能弄清楚您的模块是否存在并且已ImportError被捕获并使一切静默失败。

Python 2, without relying ImportError

Until the current answer is updated, here is the way for Python 2

import pkgutil
import importlib

if pkgutil.find_loader(mod) is not None:
    return importlib.import_module(mod)
return None

Why another answer?

A lot of answers make use of catching an ImportError. The problem with that is, that we cannot know what throws the ImportError.

If you import your existant module and there happens to be an ImportError in your module (e.g. typo on line 1), the result will be that your module does not exist. It will take you quite the amount of backtracking to figure out that your module exists and the ImportError is caught and makes things fail silently.


回答 4

go_as的答案

 python -c "help('modules');" | grep module

go_as’s answer as a one liner

 python -c "help('modules');" | grep module

回答 5

我在寻找一种方法来检查是否从命令行加载了模块时遇到了这个问题, 并希望与我分享那些对我的想法并寻找相同想法的想法:

Linux / UNIX脚本文件方法:创建文件module_help.py

#!/usr/bin/env python

help('modules')

然后确保它是可执行的: chmod u+x module_help.py

并用一个 pipetogrep

./module_help.py | grep module_name

调用内置的帮助系统。(此功能仅供交互式使用。)如果未提供任何参数,则交互式帮助系统将在解释器控制台上启动。如果参数是string,则将字符串作为模块,函数,类,方法,关键字或文档主题的名称进行查找,并在控制台上打印帮助页面。如果自变量是任何其他类型的对象,则会在该对象上生成帮助页面。

互动方式:在控制台中加载python

>>> help('module_name')

如果找到,请通过键入退出阅读 q
以退出python交互式会话,请按Ctrl+D

Windows脚本文件方法也与Linux / UNIX兼容,并且总体上更好

#!/usr/bin/env python

import sys

help(sys.argv[1])

从以下命令中调用它:

python module_help.py site  

将输出:

有关模块站点的帮助:

NAME site-将第三方软件包的模块搜索路径附加到sys.path。

FILE /usr/lib/python2.7/site.py

MODULE DOCS http://docs.python.org/library/site

DESCRIPTION

而且你必须按 q退出交互模式。

使用它未知模块:

python module_help.py lkajshdflkahsodf

将输出:

找不到“ lkajshdflkahsodf”的Python文档

然后退出。

I came across this question while searching for a way to check if a module is loaded from the command line and would like to share my thoughts for the ones coming after me and looking for the same:

Linux/UNIX script file method: make a file module_help.py:

#!/usr/bin/env python

help('modules')

Then make sure it’s executable: chmod u+x module_help.py

And call it with a pipe to grep:

./module_help.py | grep module_name

Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

Interactive method: in the console load python

>>> help('module_name')

If found quit reading by typing q
To exit the python interactive session press Ctrl + D

Windows script file method also Linux/UNIX compatible, and better overall:

#!/usr/bin/env python

import sys

help(sys.argv[1])

Calling it from the command like:

python module_help.py site  

Would output:

Help on module site:

NAME site – Append module search paths for third-party packages to sys.path.

FILE /usr/lib/python2.7/site.py

MODULE DOCS http://docs.python.org/library/site

DESCRIPTION

:

and you’d have to press q to exit interactive mode.

Using it unknown module:

python module_help.py lkajshdflkahsodf

Would output:

no Python documentation found for ‘lkajshdflkahsodf’

and exit.


回答 6

使用pkgutil中的功能之一,例如:

from pkgutil import iter_modules

def module_exists(module_name):
    return module_name in (name for loader, name, ispkg in iter_modules())

Use one of the functions from pkgutil, for example:

from pkgutil import iter_modules

def module_exists(module_name):
    return module_name in (name for loader, name, ispkg in iter_modules())

回答 7

来自AskUbuntu的更简单的if语句:如何检查Python中是否安装了模块?

import sys
print('eggs' in sys.modules)

A simpler if statement from AskUbuntu: How do I check whether a module is installed in Python?

import sys
print('eggs' in sys.modules)

回答 8

您可以编写一个脚本来尝试导入所有模块,并告诉您哪些模块发生故障以及哪些模块正在工作:

import pip


if __name__ == '__main__':
    for package in pip.get_installed_distributions():
        pack_string = str(package).split(" ")[0]
        try:
            if __import__(pack_string.lower()):
                print(pack_string + " loaded successfully")
        except Exception as e:
            print(pack_string + " failed with error code: {}".format(e))

输出:

zope.interface loaded successfully
zope.deprecation loaded successfully
yarg loaded successfully
xlrd loaded successfully
WMI loaded successfully
Werkzeug loaded successfully
WebOb loaded successfully
virtualenv loaded successfully
...

请注意,这将尝试导入所有内容,因此您会看到类似的信息,PyYAML failed with error code: No module named pyyaml因为实际的导入名称仅为yaml。因此,只要您知道自己的进口货,就可以为您解决问题。

You could just write a little script that would try to import all the modules and tell you which ones are failing and which ones are working:

import pip


if __name__ == '__main__':
    for package in pip.get_installed_distributions():
        pack_string = str(package).split(" ")[0]
        try:
            if __import__(pack_string.lower()):
                print(pack_string + " loaded successfully")
        except Exception as e:
            print(pack_string + " failed with error code: {}".format(e))

Output:

zope.interface loaded successfully
zope.deprecation loaded successfully
yarg loaded successfully
xlrd loaded successfully
WMI loaded successfully
Werkzeug loaded successfully
WebOb loaded successfully
virtualenv loaded successfully
...

Word of warning this will try to import everything so you’ll see things like PyYAML failed with error code: No module named pyyaml because the actual import name is just yaml. So as long as you know your imports this should do the trick for you.


回答 9

我写了这个辅助函数:

def is_module_available(module_name):
    if sys.version_info < (3, 0):
        # python 2
        import importlib
        torch_loader = importlib.find_loader(module_name)
    elif sys.version_info <= (3, 3):
        # python 3.0 to 3.3
        import pkgutil
        torch_loader = pkgutil.find_loader(module_name)
    elif sys.version_info >= (3, 4):
        # python 3.4 and above
        import importlib
        torch_loader = importlib.util.find_spec(module_name)

    return torch_loader is not None

I wrote this helper function:

def is_module_available(module_name):
    if sys.version_info < (3, 0):
        # python 2
        import importlib
        torch_loader = importlib.find_loader(module_name)
    elif sys.version_info <= (3, 3):
        # python 3.0 to 3.3
        import pkgutil
        torch_loader = pkgutil.find_loader(module_name)
    elif sys.version_info >= (3, 4):
        # python 3.4 and above
        import importlib
        torch_loader = importlib.util.find_spec(module_name)

    return torch_loader is not None

回答 10

您也可以importlib直接使用

import importlib

try:
    importlib.import_module(module_name)
except ImportError:
    # Handle error

You can also use importlib directly

import importlib

try:
    importlib.import_module(module_name)
except ImportError:
    # Handle error

回答 11

如果不导入其“父包”,则无法可靠地检查“虚线模块”是否可导入。如此说来,对于“如何检查Python模块是否存在”问题,有许多解决方案。

下面的解决方案解决了导入的模块即使存在也可能引发ImportError的问题。我们要将该情况与不存在该模块的情况区分开。

Python 2

import importlib
import pkgutil
import sys

def find_module(full_module_name):
    """
    Returns module object if module `full_module_name` can be imported. 

    Returns None if module does not exist. 

    Exception is raised if (existing) module raises exception during its import.
    """
    module = sys.modules.get(full_module_name)
    if module is None:
        module_path_tail = full_module_name.split('.')
        module_path_head = []
        loader = True
        while module_path_tail and loader:
            module_path_head.append(module_path_tail.pop(0))
            module_name = ".".join(module_path_head)
            loader = bool(pkgutil.find_loader(module_name))
            if not loader:
                # Double check if module realy does not exist
                # (case: full_module_name == 'paste.deploy')
                try:
                    importlib.import_module(module_name)
                except ImportError:
                    pass
                else:
                    loader = True
        if loader:
            module = importlib.import_module(full_module_name)
    return module

Python 3

import importlib

def find_module(full_module_name):
    """
    Returns module object if module `full_module_name` can be imported. 

    Returns None if module does not exist. 

    Exception is raised if (existing) module raises exception during its import.
    """
    try:
        return importlib.import_module(full_module_name)
    except ImportError as exc:
        if not (full_module_name + '.').startswith(exc.name + '.'):
            raise

There is no way to reliably check if “dotted module” is importable without importing its parent package. Saying this, there are many solutions to problem “how to check if Python module exists”.

Below solution address the problem that imported module can raise ImportError even it exists. We want to distinguish that situation from such in which module does not exist.

Python 2:

import importlib
import pkgutil
import sys

def find_module(full_module_name):
    """
    Returns module object if module `full_module_name` can be imported. 

    Returns None if module does not exist. 

    Exception is raised if (existing) module raises exception during its import.
    """
    module = sys.modules.get(full_module_name)
    if module is None:
        module_path_tail = full_module_name.split('.')
        module_path_head = []
        loader = True
        while module_path_tail and loader:
            module_path_head.append(module_path_tail.pop(0))
            module_name = ".".join(module_path_head)
            loader = bool(pkgutil.find_loader(module_name))
            if not loader:
                # Double check if module realy does not exist
                # (case: full_module_name == 'paste.deploy')
                try:
                    importlib.import_module(module_name)
                except ImportError:
                    pass
                else:
                    loader = True
        if loader:
            module = importlib.import_module(full_module_name)
    return module

Python 3:

import importlib

def find_module(full_module_name):
    """
    Returns module object if module `full_module_name` can be imported. 

    Returns None if module does not exist. 

    Exception is raised if (existing) module raises exception during its import.
    """
    try:
        return importlib.import_module(full_module_name)
    except ImportError as exc:
        if not (full_module_name + '.').startswith(exc.name + '.'):
            raise

回答 12

在django.utils.module_loading.module_has_submodule中


import sys
import os
import imp

def module_has_submodule(package, module_name):
    """
    check module in package
    django.utils.module_loading.module_has_submodule
    """
    name = ".".join([package.__name__, module_name])
    try:
        # None indicates a cached miss; see mark_miss() in Python/import.c.
        return sys.modules[name] is not None
    except KeyError:
        pass
    try:
        package_path = package.__path__   # No __path__, then not a package.
    except AttributeError:
        # Since the remainder of this function assumes that we're dealing with
        # a package (module with a __path__), so if it's not, then bail here.
        return False
    for finder in sys.meta_path:
        if finder.find_module(name, package_path):
            return True
    for entry in package_path:
        try:
            # Try the cached finder.
            finder = sys.path_importer_cache[entry]
            if finder is None:
                # Implicit import machinery should be used.
                try:
                    file_, _, _ = imp.find_module(module_name, [entry])
                    if file_:
                        file_.close()
                    return True
                except ImportError:
                    continue
            # Else see if the finder knows of a loader.
            elif finder.find_module(name):
                return True
            else:
                continue
        except KeyError:
            # No cached finder, so try and make one.
            for hook in sys.path_hooks:
                try:
                    finder = hook(entry)
                    # XXX Could cache in sys.path_importer_cache
                    if finder.find_module(name):
                        return True
                    else:
                        # Once a finder is found, stop the search.
                        break
                except ImportError:
                    # Continue the search for a finder.
                    continue
            else:
                # No finder found.
                # Try the implicit import machinery if searching a directory.
                if os.path.isdir(entry):
                    try:
                        file_, _, _ = imp.find_module(module_name, [entry])
                        if file_:
                            file_.close()
                        return True
                    except ImportError:
                        pass
                # XXX Could insert None or NullImporter
    else:
        # Exhausted the search, so the module cannot be found.
        return False

in django.utils.module_loading.module_has_submodule


import sys
import os
import imp

def module_has_submodule(package, module_name):
    """
    check module in package
    django.utils.module_loading.module_has_submodule
    """
    name = ".".join([package.__name__, module_name])
    try:
        # None indicates a cached miss; see mark_miss() in Python/import.c.
        return sys.modules[name] is not None
    except KeyError:
        pass
    try:
        package_path = package.__path__   # No __path__, then not a package.
    except AttributeError:
        # Since the remainder of this function assumes that we're dealing with
        # a package (module with a __path__), so if it's not, then bail here.
        return False
    for finder in sys.meta_path:
        if finder.find_module(name, package_path):
            return True
    for entry in package_path:
        try:
            # Try the cached finder.
            finder = sys.path_importer_cache[entry]
            if finder is None:
                # Implicit import machinery should be used.
                try:
                    file_, _, _ = imp.find_module(module_name, [entry])
                    if file_:
                        file_.close()
                    return True
                except ImportError:
                    continue
            # Else see if the finder knows of a loader.
            elif finder.find_module(name):
                return True
            else:
                continue
        except KeyError:
            # No cached finder, so try and make one.
            for hook in sys.path_hooks:
                try:
                    finder = hook(entry)
                    # XXX Could cache in sys.path_importer_cache
                    if finder.find_module(name):
                        return True
                    else:
                        # Once a finder is found, stop the search.
                        break
                except ImportError:
                    # Continue the search for a finder.
                    continue
            else:
                # No finder found.
                # Try the implicit import machinery if searching a directory.
                if os.path.isdir(entry):
                    try:
                        file_, _, _ = imp.find_module(module_name, [entry])
                        if file_:
                            file_.close()
                        return True
                    except ImportError:
                        pass
                # XXX Could insert None or NullImporter
    else:
        # Exhausted the search, so the module cannot be found.
        return False

django导入错误-没有名为core.management的模块

问题:django导入错误-没有名为core.management的模块

好的,我看到很多这些错误。我已经尝试了所有我想做的事情,但是还没有弄清楚。

我正在开发运行python 2.5和Django 1.3的开发服务器。在解压缩tar.gz下载文件后,使用python setup.py install安装了Django 1.3。

一切正常,我很少需要运行,manage.py但是正在尝试使用新的staticfiles应用程序,并且遇到了问题。

python manage.py collectstatic
Traceback (most recent call last):
  File "manage.py", line 2, in <module>
    from django.core.management import execute_manager
ImportError: No module named core.management

好的,所以我有PATH问题。

Django安装中,我再次检查site-packages目录。

python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"
/usr/lib/python2.5/site-packages

好的,让我们检查一下我拥有的东西,echo $ PYTHON_PATH为空,所以我将其设置为

export PYTHON_PATH=/usr/lib/python2.5/site-packages/django

仍然没有运气。让我们检查sys.path怎么说

>>> import sys
>>> print sys.path
['', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/site-packages/django', '/var/lib/python-support/python2.5']

路径在那里,我什至用内容创建了/usr/lib/python2.5/site-packages/django.pth

cat /usr/lib/python2.5/site-packages/django.pth 
/usr/lib/python2.5/site-packages/django/

有人知道这里发生了什么吗?

我在通往的道路上发现了一个符号链接,但没有出现新的错误。

python manage.py collectstatic
Traceback (most recent call last):
  File "manage.py", line 14, in <module>
    execute_manager(settings)
  File "/usr/lib/python2.5/site-packages/django/core/management/__init__.py", line 438, in execute_manager
    utility.execute()
  File "/usr/lib/python2.5/site-packages/django/core/management/__init__.py", line 349, in execute
    version=get_version(),
  File "/usr/lib/python2.5/site-packages/django/__init__.py", line 12, in get_version
    from django.utils.version import get_svn_revision
ImportError: No module named utils.version

我还尝试创建一个新项目,以查看是否存在任何问题,并得到相同的utils.version错误。

侧面节点:#django的Unode帮助了我一点,在同一台计算机上设置了virtualenv并克服了错误,因此仍不确定此处的实际安装如何,但是似乎不在django项目中,而在django中/ python安装。

Ok, I see plenty of these errors around. I have tried everything I know to do and have yet to figure this out.

I am working on a development server running python 2.5 and Django 1.3. Django 1.3 was installed using python setup.py install after unpacking the tar.gz download.

All works well, I seldom have the need to run manage.py but am trying to use the new staticfiles app and am running into problems.

python manage.py collectstatic
Traceback (most recent call last):
  File "manage.py", line 2, in <module>
    from django.core.management import execute_manager
ImportError: No module named core.management

Ok, so I have PATH issue.

From Django install I double check my site-packages directory.

python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"
/usr/lib/python2.5/site-packages

Ok, let’s check out what I have, echo $PYTHON_PATH was empty, so I set it

export PYTHON_PATH=/usr/lib/python2.5/site-packages/django

Still no luck. Lets check what sys.path has to say

>>> import sys
>>> print sys.path
['', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/site-packages/django', '/var/lib/python-support/python2.5']

path is there, I even created /usr/lib/python2.5/site-packages/django.pth with contents

cat /usr/lib/python2.5/site-packages/django.pth 
/usr/lib/python2.5/site-packages/django/

Anyone got an clues to what is going on here?

I found a symlink further up the path that was getting in the way, but no on to a new error.

python manage.py collectstatic
Traceback (most recent call last):
  File "manage.py", line 14, in <module>
    execute_manager(settings)
  File "/usr/lib/python2.5/site-packages/django/core/management/__init__.py", line 438, in execute_manager
    utility.execute()
  File "/usr/lib/python2.5/site-packages/django/core/management/__init__.py", line 349, in execute
    version=get_version(),
  File "/usr/lib/python2.5/site-packages/django/__init__.py", line 12, in get_version
    from django.utils.version import get_svn_revision
ImportError: No module named utils.version

I also tried creating a new project to see if there were any issues there and get the same utils.version error.

Side node: Unode from #django helped me a bit, set up virtualenv on same machine and got past the errors so still not sure what is up with this actual install here, but it seems to not be in the django projects but in the django/python install.


回答 0

如果像我一样,您正在virtualenv中运行django,并收到此错误,请查看您的manage.py。第一行应定义用于运行脚本的python可执行文件。这应该是您的virtualenv的python的路径,但这是/ usr / bin / python之类的错误,它不是相同的路径,并且将使用全局python环境(并且缺少软件包)。只需将路径更改为virtualenv中python可执行文件的路径即可。

您也可以用替换您的shebang线#!/usr/bin/env python。如果您首先激活了virtualenv,这应该使用适当的python环境和解释器(我假设您知道如何执行此操作)。

If, like me, you are running your django in a virtualenv, and getting this error, look at your manage.py. The first line should define the python executable used to run the script. This should be the path to your virtualenv’s python, but it is something wrong like /usr/bin/python, which is not the same path and will use the global python environment (and packages will be missing). Just change the path into the path to the python executable in your virtualenv.

You can also replace your shebang line with #!/usr/bin/env python. This should use the proper python environment and interpreter provided that you activate your virtualenv first (I assume you know how to do this).


回答 1

如果您在virtualenv中,则需要先激活它,然后才能运行./manage.py’command’

source path/to/your/virtualenv/bin/activate

如果您在.bash_profile或.bashrc中配置workon

workon yourvirtualenvname

*请不要编辑您的manage.py文件,可能不是正确的方法,并且可能会给您将来的错误

If you are in a virtualenv you need to activate it before you can run ./manage.py ‘command’

source path/to/your/virtualenv/bin/activate

if you config workon in .bash_profile or .bashrc

workon yourvirtualenvname

*please dont edit your manage.py file maybe works by isnt the correct way and could give you future errors


回答 2

我遇到了同样的问题,因为我以超级用户身份安装Django,因此不在我的virtualenv中。你不应该做sudo pip install Django

而是以这种方式安装它:

$ source ./bin/activate
$ pip install Django

I had the same problem because I was installing Django as a super user, thus not in my virtualenv. You should not do sudo pip install Django

Instead, install it this way:

$ source ./bin/activate
$ pip install Django

回答 3

请用pip重新安装django:

sudo pip install --upgrade django==1.3

(将1.3替换为您的Django版本)

Please, reinstall django with pip:

sudo pip install --upgrade django==1.3

(Replace 1.3 to your django version)


回答 4

众所周知,这是一个路径问题。

我的自定义软件包的基础与/ etc / profile中设置的目录共享一个名称。软件包位于Web服务器的其他位置。因此,我从$ PYTHONPATH中删除了令人反感的条目,并且一切顺利!

谢谢您的帮助。

As known this was a path issue.

the base of my custom packages shared a name with a directory set in a /etc/profile. The packages were in a different location however for the webserver. So I removed the offending entries from my $PYTHONPATH and was good to go!

Thanks for the help.


回答 5

此问题的另一个可能原因是,您的操作系统默认情况下运行python3。

您必须明确地执行以下操作: python2 manage.py

或您需要编辑的shebang manage.py,如下所示:

#!/usr/bin/env python2

或者,如果您使用的是python3:

#!/usr/bin/env python3

Another possible reason for this problem is that your OS runs python3 by default.

Either you have to explicitly do: python2 manage.py

or you need to edit the shebang of manage.py, like so:

#!/usr/bin/env python2

or if you are using python3:

#!/usr/bin/env python3

回答 6

而试图在运行嵌入式系统(当然使用Django的)我有这个错误树莓派2(并且不是一个VM

运行此:

 sudo pip install Django

搞定了!

  • 以防万一使用Raspbian / Jessie的人得到了这个

I had this error while trying to run an embedded system (using django of course) on a Raspberry Pi 2 (and not a VM)

Running this:

 sudo pip install Django

Made the trick!

  • just in case a fellow using Raspbian/Jessie gets this

回答 7

您可能正在使用virtualenvwrapper。不要忘记通过运行以下命令来选择您的环境:

$ workon env_name

You are probably using virtualenvwrapper. Don’t forget to select your enviroment by running:

$ workon env_name

回答 8

对我来说,我的服务器使用的是Python 2.4。我只是查找了安装在服务器上的Python 2.7,并创建了一个别名。

alias python=python2.7

如果您需要了解更多信息,我在这里找到了解决方案

For me, my server was using Python 2.4. I simply looked up Python 2.7, which was installed on my server, and created an alias.

alias python=python2.7

If you need to know more, I found the solution here


回答 9

尝试创建新应用时遇到了同样的问题。如果您编写python manage.py startapp myapp,则它将查找usr / bin / python。但是您需要这个“ python ”,它位于虚拟环境路径的/ bin目录中。我通过提及virtualenv的python路径来解决此问题,如下所示:

<env path>/bin/python manage.py startapp myapp

I was getting the same problem while I trying to create a new app. If you write python manage.py startapp myapp, then it looks for usr/bin/python. But you need this “python” which is located in /bin directory of your virtual env path. I solved this by mentioning the virtualenv’s python path just like this:

<env path>/bin/python manage.py startapp myapp

回答 10

尝试更改您的manage.py的第一行。

更改

#!/usr/bin/python

通过

#!/usr/bin/env python

Try change your first line of manage.py.

Change

#!/usr/bin/python

by

#!/usr/bin/env python

回答 11

python3 manage.py runserver

检查Python版本

python3 manage.py runserver

Check version of Python


回答 12

解决了!!!

在寻找了年龄并尝试了所有其他不可行的建议之后,我终于找到了适合我的设置的解决方案。

我的设置/方案:

  • Windows,Python27
  • 我的Django项目通过svn签出
  • 在新文件夹中运行python manage.py runserver时,出现导入错误
  • python manage.py runserver曾经在原始文件夹(我会提交更改)中使用,直到删除它为止

删除manage.py同一目录中名为django的所有文件夹

没错…删除文件夹“ django”后,该文件夹仅包含__init__.py文件…我可以再次运行服务器!

不知道为什么

Solved it!!!

After searching for ages and trying all these other suggestions which didn’t work, I finally found the solution for my setup.

My setup/scenario:

  • Windows, Python27
  • My django project is checked out via svn
  • when running python manage.py runserver in the new folder, I got the import error
  • python manage.py runserver used to work in the original folder (which I would commit changes from) until I deleted it

Solution

Remove any the folder named django in the same directory of manage.py

Thats right…as soon as I removed the folder “django” which only contained a __init__.py file…I could run the server again!

Have no idea why though


回答 13

对于使用Django 1.6或更高版本的用户,请注意execute_manager已删除。有张贴在第二SO答案的解决方案在这里

For those of you using Django 1.6 or newer, note that execute_manager was removed. There is a solution posted in the second SO answer here.


回答 14

将python python路径存储在一个变量中并执行。

python_path= `which python` 
$python_path manage.py runserver

Store the python python path in a variable and execute.This would include the otherwise missing packages.

python_path= `which python` 
$python_path manage.py runserver

回答 15

我有一个类似的问题。PyCharm无法运行服务器,但是我可以从命令行运行它。我尝试使用哪个python,然后确保PyCharm是相同的解释器,然后一切正常。

I had a similar problem. PyCharm couldn’t run the server but I could run it from the command line. I tried which python and then made sure that PyCharm was same interpreter and then everything worked OK.


回答 16

当未安装django时,通常会发生此错误。如果您已经安装了django但仍然遇到相同的错误,则必须在单独的虚拟环境中工作。您还需要在虚拟环境中安装django。当您在虚拟机的外壳中时,只需执行以下操作:

pip安装Django

这是因为虚拟机具有单独的文件系统,即使将Django安装在您的系统上,它也无法识别。

This error usually occurs when django is not installed. If you have already installed django but still getting the same error, then you must be working in separate virtual environment. You need to install django in your virtual environmnent as well. When you are in shell of virtual machine simply do this:

pip install django

It is because virtual machine has separate file system, it doesn’t recognize django even if it is installed on your system.


回答 17

我通过将#PATH =“ $ VIRTUAL_ENV / bin:$ PATH”更改为PATH =“ $ PATH:$ VIRTUAL_ENV / bin”来解决此问题,由于对我不明显的原因,virtualenv目录中的python可执行文件看不到Django,但安装的Python呢。

I fixed this problem by changing #PATH=”$VIRTUAL_ENV/bin:$PATH” to PATH=”$PATH:$VIRTUAL_ENV/bin” For reasons not obvious to me the python executable in the virtualenv dir does not see django but the normally installed python does.


回答 18

================================解决方案=============== =========================

首先转到:virtualenv

通过运行以下命令:source bin / activate

并安装django,因为您收到与“ import django”相关的错误:

pip install django

然后运行:

python manage.py runserver

(注意:请将“ runserver”更改为要运行的程序名称)

对于同一问题,它在我的情况下有效。=================================提要================= =========================

ERROR:
(Development) Rakeshs-MacBook-Pro:src rakesh$ python manage.py runserver
Traceback (most recent call last):
  File "manage.py", line 8, in <module>
    from django.core.management import execute_from_command_line
ModuleNotFoundError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 14, in <module>
    import django
ModuleNotFoundError: No module named 'django'

在处理上述异常期间,发生了另一个异常:

Traceback (most recent call last):
  File "manage.py", line 17, in <module>
    "Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
(Development) Rakeshs-MacBook-Pro:src rakesh$ 
(Development) Rakeshs-MacBook-Pro:src rakesh$ 
(Development) Rakeshs-MacBook-Pro:src rakesh$ python -Wall manage.py test
Traceback (most recent call last):
  File "manage.py", line 8, in <module>
    from django.core.management import execute_from_command_line
ModuleNotFoundError: No module named 'django'

在处理上述异常期间,发生了另一个异常:

Traceback (most recent call last):
  File "manage.py", line 14, in <module>
    import django
ModuleNotFoundError: No module named 'django'

在处理上述异常期间,发生了另一个异常:

Traceback (most recent call last):
  File "manage.py", line 17, in <module>
    "Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?

安装Django之后:

(Development) MacBook-Pro:src rakesh$ pip install django
Collecting django
  Downloading https://files.pythonhosted.org/packages/51/1a/e0ac7886c7123a03814178d7517dc822af0fe51a72e1a6bff26153103322/Django-2.1-py3-none-any.whl (7.3MB)
    100% |████████████████████████████████| 7.3MB 1.1MB/s 
Collecting pytz (from django)
  Downloading https://files.pythonhosted.org/packages/30/4e/27c34b62430286c6d59177a0842ed90dc789ce5d1ed740887653b898779a/pytz-2018.5-py2.py3-none-any.whl (510kB)
    100% |████████████████████████████████| 512kB 4.7MB/s 
Installing collected packages: pytz, django

解决后:

(Development) MacBook-Pro:src rakesh$ python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

August 05, 2018 - 04:39:02
Django version 2.1, using settings 'trydjango.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[05/Aug/2018 04:39:15] "GET / HTTP/1.1" 200 16348
[05/Aug/2018 04:39:15] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423
[05/Aug/2018 04:39:15] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 82564
[05/Aug/2018 04:39:15] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 81348
[05/Aug/2018 04:39:15] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 80304
Not Found: /favicon.ico
[05/Aug/2018 04:39:16] "GET /favicon.ico HTTP/1.1" 404 1976

祝好运!!

==================================SOLUTION=========================================

First goto: virtualenv

by running the command: source bin/activate

and install django because you are getting the error related to ‘import django’:

pip install django

Then run:

python manage.py runserver

(Note: please change ‘runserver’ to the program name you want to run)

For the same issue, it worked in my case. ==================================Synopsis=========================================

ERROR:
(Development) Rakeshs-MacBook-Pro:src rakesh$ python manage.py runserver
Traceback (most recent call last):
  File "manage.py", line 8, in <module>
    from django.core.management import execute_from_command_line
ModuleNotFoundError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 14, in <module>
    import django
ModuleNotFoundError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 17, in <module>
    "Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
(Development) Rakeshs-MacBook-Pro:src rakesh$ 
(Development) Rakeshs-MacBook-Pro:src rakesh$ 
(Development) Rakeshs-MacBook-Pro:src rakesh$ python -Wall manage.py test
Traceback (most recent call last):
  File "manage.py", line 8, in <module>
    from django.core.management import execute_from_command_line
ModuleNotFoundError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 14, in <module>
    import django
ModuleNotFoundError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 17, in <module>
    "Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?

AFTER INSTALLATION of django:

(Development) MacBook-Pro:src rakesh$ pip install django
Collecting django
  Downloading https://files.pythonhosted.org/packages/51/1a/e0ac7886c7123a03814178d7517dc822af0fe51a72e1a6bff26153103322/Django-2.1-py3-none-any.whl (7.3MB)
    100% |████████████████████████████████| 7.3MB 1.1MB/s 
Collecting pytz (from django)
  Downloading https://files.pythonhosted.org/packages/30/4e/27c34b62430286c6d59177a0842ed90dc789ce5d1ed740887653b898779a/pytz-2018.5-py2.py3-none-any.whl (510kB)
    100% |████████████████████████████████| 512kB 4.7MB/s 
Installing collected packages: pytz, django

AFTER RESOLVING:

(Development) MacBook-Pro:src rakesh$ python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

August 05, 2018 - 04:39:02
Django version 2.1, using settings 'trydjango.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[05/Aug/2018 04:39:15] "GET / HTTP/1.1" 200 16348
[05/Aug/2018 04:39:15] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423
[05/Aug/2018 04:39:15] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 82564
[05/Aug/2018 04:39:15] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 81348
[05/Aug/2018 04:39:15] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 80304
Not Found: /favicon.ico
[05/Aug/2018 04:39:16] "GET /favicon.ico HTTP/1.1" 404 1976

Good luck!!


回答 19

您的项目是使用django1.3之前的旧版本django-admin.py创建的

要解决此问题,请创建另一个django项目并复制其manage.py并将其粘贴到旧的项目中

your project is created using an old version of django-admin.py, older than django1.3

to fix this create another django project and copy its manage.py and paste it in the old one


回答 20

完全同意这是一个路径问题,但是首先,我遇到了同样的错误。这是由于在设置虚拟环境时为我的Python可执行文件使用了相对路径的错误。我这样做了:

virtualenv -p ~/python_runtimes/2.7.3/bin/python venv2.7.3 --distribute

相反,我不得不给出Python可执行文件的完整路径。

哈林HTH

Agreed completely that this is a path issue but fwiw, I had this same error. It was due to the mistake of using a relative path for my Python executable when setting up my virtual environment. I had done this:

virtualenv -p ~/python_runtimes/2.7.3/bin/python venv2.7.3 --distribute

Instead I had to give the full path to the Python executable.

HTH, Harlin


回答 21

来源〜/ blog-venv / bin / activate

在此处选择您的virtualenv替换“ blog-venv”。

source ~/blog-venv/bin/activate

pick your virtualenv to replace “blog-venv” here.


回答 22

确保您在路径上使用正确的目录运行正确的Python实例。就我而言,此错误是python由偶然运行可执行文件引起的-我实际上是在python2.7框架和库下安装了Django 。由于virtualenv也可能发生相同的情况。

Be sure you’re running the right instance of Python with the right directories on the path. In my case, this error resulted from running the python executable by accident – I had actually installed Django under the python2.7 framework & libraries. The same could happen as a result of virtualenv as well.


回答 23

好的,它像这样:

您已经创建了一个虚拟环境,而django模块仅属于该环境。由于virtualenv会将其自身与其他所有事物隔离开,因此您会看到这一点。

进行以下操作以获得进一步的帮助:

http://www.swegler.com/becky/blog/2011/08/27/python-django-mysql-on-windows-7-part-i-getting-started/

1.您可以切换到虚拟环境存储的目录,然后运行django模块。

2.或者您可以通过运行pip或easy_install将django全局安装到python-> site-packages

使用pip的命令:pip install django

然后这样做:

导入django打印(django.get_version())(取决于您使用的python版本。这适用于python 3+系列)

然后您可以运行以下命令:python manage.py runserver并通过输入:localhost:8000在Web浏览器上进行检查,您应该看到django驱动的页面。

希望这可以帮助。

Okay so it goes like this:

You have created a virtual environment and django module belongs to that environment only.Since virtualenv isolates itself from everything else,hence you are seeing this.

go through this for further assistance:

http://www.swegler.com/becky/blog/2011/08/27/python-django-mysql-on-windows-7-part-i-getting-started/

1.You can switch to the directory where your virtual environment is stored and then run the django module.

2.Alternatively you can install django globally to your python->site-packages by either running pip or easy_install

Command using pip: pip install django

then do this:

import django print (django.get_version()) (depending on which version of python you use.This for python 3+ series)

and then you can run this: python manage.py runserver and check on your web browser by typing :localhost:8000 and you should see django powered page.

Hope this helps.


回答 24

我在发出startapp命令之前“之前”将新应用程序的名称包含在settings.py的INSTALLED_APPS列表中。删除列表条目后,就可以创建应用了。

I included the name of the new App to the INSTALLED_APPS list in the settings.py “before” I issued the startapp command. Once I removed the list entry, I could create the app.


回答 25

我通过使用’django-admin’命令来解决此问题,如下所示:

django-admin startproject _project_name

只需删除附加到“ django-admin”的“ .py”

I solved this problem by using ‘django-admin’ command as following instead:

django-admin startproject _project_name

just remove the “.py” attached to “django-admin”


回答 26

调用一个应用程序site也可以重现此问题。

Having an application called site can reproduce this issue either.


回答 27

我之所以忘记了,是因为我忘记使用来安装Django pip -U,因此它仅适用于运行Django应用的用户。要运行manage.py我必须做

sudo su -s /bin/bash MY_DJANGO_USER
/PATH/TO/MY/APP/manage.py

I got this due to forgetting that I installed Django using pip -U, so it was only available to the user running my Django app. To run manage.py I had to do

sudo su -s /bin/bash MY_DJANGO_USER
/PATH/TO/MY/APP/manage.py

回答 28

你们所有人都没有提到有人“像我”会在安装virtualenv之前安装django …因此,对于所有此类人,如果这样做,…在激活virtualenv..i之后重新安装django。希望这可以帮助

all of you guys didn’t mention a case where someone “like me” would install django befor installing virtualenv…so for all the people of my kind ther if you did that…reinstall django after activating the virtualenv..i hope this helps


相对导入-ModuleNotFoundError:没有名为x的模块

问题:相对导入-ModuleNotFoundError:没有名为x的模块

这是我第一次真正坐下来尝试python 3,但似乎失败了。我有以下两个文件:

  1. test.py
  2. config.py

config.py中定义了一些函数以及一些变量。我将其简化为以下内容:

config.py

debug = True

test.py

import config
print (config.debug)

我也有一个 __init__.py

但是,出现以下错误:

ModuleNotFoundError: No module named 'config'

我知道py3约定要使用绝对导入:

from . import config

但是,这导致以下错误:

ImportError: cannot import name 'config'

因此,我对此无所适从……任何帮助将不胜感激。:)

This is the first time I’ve really sat down and tried python 3, and seem to be failing miserably. I have the following two files:

  1. test.py
  2. config.py

config.py has a few functions defined in it as well as a few variables. I’ve stripped it down to the following:

config.py

debug = True

test.py

import config
print (config.debug)

I also have an __init__.py

However, I’m getting the following error:

ModuleNotFoundError: No module named 'config'

I’m aware that the py3 convention is to use absolute imports:

from . import config

However, this leads to the following error:

ImportError: cannot import name 'config'

So I’m at a loss as to what to do here… Any help is greatly appreciated. :)


回答 0

TL; DR:由于模块不是包的一部分,因此无法从执行的文件中进行相对导入__main__

绝对导入 -导入可用的内容sys.path

相对导入 -相对于当前模块的导入,必须是包的一部分

如果您以完全相同的方式运行两个变体,则其中一个应该可以工作。无论如何,这是一个示例,应该可以帮助您了解正在发生的事情,让我们添加main.py具有总体目录结构的另一个文件,如下所示:

.
./main.py
./ryan/__init__.py
./ryan/config.py
./ryan/test.py

让我们更新test.py以查看发生了什么:

# config.py
debug = True


# test.py
print(__name__)

try:
    # Trying to find module in the parent package
    from . import config
    print(config.debug)
    del config
except ImportError:
    print('Relative import failed')

try:
    # Trying to find module on sys.path
    import config
    print(config.debug)
except ModuleNotFoundError:
    print('Absolute import failed')
# main.py
import ryan.test

让我们先运行test.py:

$ python ryan/test.py
__main__
Relative import failed
True

这里的“测试” __main__模块,不知道属于什么包。但是import config应该可以,因为该ryan文件夹将被添加到sys.path中。

让我们运行main.py代替:

$ python main.py
ryan.test
True
Absolute import failed

这里的测试在“ ryan”包中,可以执行相对的导入。import config失败,因为Python 3中不允许隐式相对导入。

希望这会有所帮助。

PS:如果您坚持使用Python 3,则__init__.py文件中不再需要。

TL;DR: You can’t do relative imports from the file you execute since __main__ module is not a part of a package.

Absolute imports – import something available on sys.path

Relative imports – import something relative to the current module, must be a part of a package

If you’re running both variants in exactly the same way, one of them should work. Here is an example that should help you understand what’s going on. Let’s add another main.py file with the overall directory structure like this:

.
./main.py
./ryan/__init__.py
./ryan/config.py
./ryan/test.py

And let’s update test.py to see what’s going on:

# config.py
debug = True
# test.py
print(__name__)

try:
    # Trying to find module in the parent package
    from . import config
    print(config.debug)
    del config
except ImportError:
    print('Relative import failed')

try:
    # Trying to find module on sys.path
    import config
    print(config.debug)
except ModuleNotFoundError:
    print('Absolute import failed')
# main.py
import ryan.test

Let’s run test.py first:

$ python ryan/test.py
__main__
Relative import failed
True

Here “test” is the __main__ module and doesn’t know anything about belonging to a package. However import config should work, since the ryan folder will be added to sys.path.

Let’s run main.py instead:

$ python main.py
ryan.test
True
Absolute import failed

And here test is inside of the “ryan” package and can perform relative imports. import config fails since implicit relative imports are not allowed in Python 3.

Hope this helped.

P.S.: If you’re sticking with Python 3 there is no more need for __init__.py files.


回答 1

我想到了。非常令人沮丧,尤其是来自python2。

.无论模块是相对的还是绝对的,都必须向模块添加a 。

我创建目录设置如下。

/main.py
--/lib
  --/__init__.py
  --/mody.py
  --/modx.py

修改器

def does_something():
    return "I gave you this string."

from modx import does_something

def loaded():
    string = does_something()
    print(string)

main.py

from lib import mody

mody.loaded()

当我执行main时,会发生这种情况

$ python main.py
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    from lib import mody
  File "/mnt/c/Users/Austin/Dropbox/Source/Python/virtualenviron/mock/package/lib/mody.py", line 1, in <module>
    from modx import does_something
ImportError: No module named 'modx'

我运行了2to3,核心输出是

RefactoringTool: Refactored lib/mody.py
--- lib/mody.py (original)
+++ lib/mody.py (refactored)
@@ -1,4 +1,4 @@
-from modx import does_something
+from .modx import does_something

 def loaded():
     string = does_something()
RefactoringTool: Files that need to be modified:
RefactoringTool: lib/modx.py
RefactoringTool: lib/mody.py

我不得不修改mody.py的import语句来修复它

try:
    from modx import does_something
except ImportError:
    from .modx import does_something


def loaded():
    string = does_something()
    print(string)

然后我再次运行main.py并获得了预期的输出

$ python main.py
I gave you this string.

最后,只是清理一下并使其在2到3之间可移植。

from __future__ import absolute_import
from .modx import does_something

I figured it out. Very frustrating, especially coming from python2.

You have to add a . to the module, regardless of whether or not it is relative or absolute.

I created the directory setup as follows.

/main.py
--/lib
  --/__init__.py
  --/mody.py
  --/modx.py

modx.py

def does_something():
    return "I gave you this string."

mody.py

from modx import does_something

def loaded():
    string = does_something()
    print(string)

main.py

from lib import mody

mody.loaded()

when I execute main, this is what happens

$ python main.py
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    from lib import mody
  File "/mnt/c/Users/Austin/Dropbox/Source/Python/virtualenviron/mock/package/lib/mody.py", line 1, in <module>
    from modx import does_something
ImportError: No module named 'modx'

I ran 2to3, and the core output was this

RefactoringTool: Refactored lib/mody.py
--- lib/mody.py (original)
+++ lib/mody.py (refactored)
@@ -1,4 +1,4 @@
-from modx import does_something
+from .modx import does_something

 def loaded():
     string = does_something()
RefactoringTool: Files that need to be modified:
RefactoringTool: lib/modx.py
RefactoringTool: lib/mody.py

I had to modify mody.py’s import statement to fix it

try:
    from modx import does_something
except ImportError:
    from .modx import does_something


def loaded():
    string = does_something()
    print(string)

Then I ran main.py again and got the expected output

$ python main.py
I gave you this string.

Lastly, just to clean it up and make it portable between 2 and 3.

from __future__ import absolute_import
from .modx import does_something

回答 2

设置PYTHONPATH也可以解决此问题。

这是在Windows上可以完成的方法

set PYTHONPATH=.

Setting PYTHONPATH can also help with this problem.

Here is how it can be done on Windows

set PYTHONPATH=.


回答 3

您必须将模块的路径附加到PYTHONPATH


对于UNIX(Linux,OSX等)

export PYTHONPATH="${PYTHONPATH}:/path/to/your/module/"

对于Windows

set PYTHONPATH=%PYTHONPATH%;C:\path\to\your\module\

You have to append your project’s path to PYTHONPATH and make sure to use absolute imports.


For UNIX (Linux, OSX, …)

export PYTHONPATH="${PYTHONPATH}:/path/to/your/project/"

For Windows

set PYTHONPATH=%PYTHONPATH%;C:\path\to\your\project\

Absolute imports

Assuming that we have the following project structure,

└── myproject
    ├── mypackage
    │   ├── a.py
    └── anotherpackage
        ├── b.py
        ├── c.py
        └── mysubpackage
            └── d.py

just make sure to reference each import starting from the project’s root directory. For instance,

# in module a.py
import anotherpackage.mysubpackage.d

# in module b
import anotherpackage.c
import mypackage.a

回答 4

试过你的例子

from . import config

得到了以下SystemError:
/usr/bin/python3.4 test.py
Traceback(最近一次调用最近):
文件“ test.py”,第1行,位于
中。导入配置
SystemError:父模块“”未加载,无法执行相对导入


这对我有用:

import config
print('debug=%s'%config.debug)

>>>debug=True

使用Python:3.4.2测试-PyCharm 2016.3.2


除了此PyCharm,您还可以导入该名称
您必须单击,config然后出现帮助图标

Tried your example

from . import config

got the following SystemError:
/usr/bin/python3.4 test.py
Traceback (most recent call last):
File “test.py”, line 1, in
from . import config
SystemError: Parent module ” not loaded, cannot perform relative import


This will work for me:

import config
print('debug=%s'%config.debug)

>>>debug=True

Tested with Python:3.4.2 – PyCharm 2016.3.2


Beside this PyCharm offers you to Import this name.
You hav to click on config and a help icon appears.


回答 5

您只需将以下文件添加到测试目录中,然后python将在测试之前运行它

__init__.py file

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

You can simply add following file to your tests directory, and then python will run it before the tests

__init__.py file

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

回答 6

PYTHONPATH在根项目目录中设置环境变量。

考虑类UNIX:

export PYTHONPATH=.

Set PYTHONPATH environment variable in root project directory.

Considering UNIX-like:

export PYTHONPATH=.

回答 7

此示例在Python 3.6上有效。

我建议进入Run -> Edit ConfigurationsPyCharm,删除那里的所有条目,然后尝试再次通过PyCharm运行代码。

如果这不起作用,请检查项目解释器(“设置”->“项目解释器”)并运行默认配置(“运行”->“编辑配置…”)。

This example works on Python 3.6.

I suggest going to Run -> Edit Configurations in PyCharm, deleting any entries there, and trying to run the code through PyCharm again.

If that doesn’t work, check your project interpreter (Settings -> Project Interpreter) and run configuration defaults (Run -> Edit Configurations…).


回答 8

在调用模块之前,声明正确的sys.path列表:

import os, sys

#'/home/user/example/parent/child'
current_path = os.path.abspath('.')

#'/home/user/example/parent'
parent_path = os.path.dirname(current_path)

sys.path.append(parent_path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'child.settings')

Declare correct sys.path list before you call module:

import os, sys

#'/home/user/example/parent/child'
current_path = os.path.abspath('.')

#'/home/user/example/parent'
parent_path = os.path.dirname(current_path)

sys.path.append(parent_path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'child.settings')

回答 9

如原始帖子的评论中所述,这似乎是我出于任何原因使用的python解释器的问题,而不是python脚本出了点问题。我从WinPython包切换到了python.org上的官方python 3.6,它工作得很好。感谢大家的帮助:)

As was stated in the comments to the original post, this seemed to be an issue with the python interpreter I was using for whatever reason, and not something wrong with the python scripts. I switched over from the WinPython bundle to the official python 3.6 from python.org and it worked just fine. thanks for the help everyone :)


回答 10

如果您使用的是python 3+,请尝试添加以下行

import os, sys
dir_path = os.path.dirname(os.path.realpath(__file__))
parent_dir_path = os.path.abspath(os.path.join(dir_path, os.pardir))
sys.path.insert(0, parent_dir_path)

If you are using python 3+ then try adding below lines

import os, sys
dir_path = os.path.dirname(os.path.realpath(__file__))
parent_dir_path = os.path.abspath(os.path.join(dir_path, os.pardir))
sys.path.insert(0, parent_dir_path)

回答 11

尝试

from . import config

这是从同一文件夹级别导入的。如果您直接尝试导入,则假定它是下属

Try

from . import config

What that does is import from the same folder level. If you directly try to import it assumes it’s a subordinate


自动创建requirements.txt

问题:自动创建requirements.txt

有时我从那里下载python源代码,github却不知道如何安装所有依赖项。如果没有requirements.txt文件,则必须手动创建。问题是:给定python源代码目录,是否可以requirements.txt从import部分自动创建?

Sometimes I download the python source code from github and don’t know how to install all the dependencies. If there is no requirements.txt file I have to create it by hands. The question is: Given the python source code directory is it possible to create requirements.txt automatically from the import section?


回答 0

如果您使用虚拟环境,pip freeze > requirements.txt就可以了。IF NOTpigar将是您不错的选择。

顺便说一句,我不保证它能在2.6下使用。

更新

建议使用Pipenv或其他工具来改善开发流程。

对于Python 3,请在下面使用

pip3 freeze > requirements.txt

If you use virtual environment, pip freeze > requirements.txt just fine. IF NOT, pigar will be a good choice for you.

By the way, I do not ensure it will work with 2.6.

UPDATE:

Pipenv or other tools is recommended for improving your development flow.

For Python 3 use below

pip3 freeze > requirements.txt

回答 1

您可以使用以下代码来生成requirements.txt文件:

pip install pipreqs

pipreqs /path/to/project

与pipreqs相关的更多信息可以在这里找到。

有时您会碰到pip freeze,但这会保存环境中的所有程序包,包括您当前项目中未使用的程序包。

You can use the following code to generate a requirements.txt file:

pip install pipreqs

pipreqs /path/to/project

more info related to pipreqs can be found here.

Sometimes you come across pip freeze, but this saves all packages in the environment including those that you don’t use in your current project.


回答 2

就我而言,我使用的是Anaconda,因此从我的环境中的conda终端运行以下命令即可解决该问题,并自动为我创建了此需求txt文件:

conda list -e > requirements.txt

摘自Github链接pratos / condaenv.txt

如果看到错误,并且您正在使用anaconda,请尝试使用.yml选项:

conda env export > <environment-name>.yml

供其他人使用的环境…或者如果要在其他计算机上创建新环境:conda env create -f .yml

.yml选项在这里找到

In my case, I use Anaconda, so running the following command from conda terminal inside my environment solved it, and created this requirements txt file for me automatically:

conda list -e > requirements.txt

This was taken from this Github link pratos/condaenv.txt

If an error been seen, and you are using anaconda, try to use the .yml option:

conda env export > <environment-name>.yml

For other person to use the environment…Or if you are creating a new enviroment on other machine: conda env create -f .yml

.yml option been found here


回答 3

确保为python3.7运行pip3。

pip3 freeze >> yourfile.txt

在执行上述命令之前,请确保已创建虚拟环境。

python3:

pip3 install virtualenv
python3 -m venv <myenvname> 

python2

pip install virtualenv
virtualenv <myenvname>

之后,将您的源代码放在目录中。如果您现在运行python文件,则可能在使用非本机模块时无法启动。您可以安装那些正在运行的模块

pip3 install <module> or pip install <module> 

除了您所在的环境,这不会影响您的整个模块列表。

现在,您可以在顶部执行命令,现在有了一个需求文件,其中仅包含您在虚拟环境中安装的模块。现在,您可以在顶部运行命令。

我建议大家使用环境,因为这样的事情会使事情变得容易。

希望这会有所帮助。

Make sure to run pip3 for python3.7.

pip3 freeze >> yourfile.txt

Before executing the above command make sure you have created a virtual environment.

python3:

pip3 install virtualenv
python3 -m venv <myenvname> 

python2:

pip install virtualenv
virtualenv <myenvname>

After that put your source code in the directory. If you run the python file now, probably It won’t launch If you are using non-native modules. You can install those modules runing

pip3 install <module> or pip install <module> 

This will not affect you entire module list except the environment you are In.

Now you can execute the command at the top and now you have a requirements file which contains only the modules you installed in the virtual environment. Now you can run the command at the top.

I advise everyone to use environments as It makes things easier when It comes to stuff like this.

Hope this helped.


回答 4

如果与我面临同样的问题,即不在虚拟环境上,并且想要特定项目或从所选文件夹(包括子文件夹)和pipreqs获得requirements.txt,则不支持。

您可以使用 :

import os
import sys
from fuzzywuzzy import fuzz
import subprocess

path = "C:/Users/Username/Desktop/DjangoProjects/restAPItest"


files = os.listdir(path)
pyfiles = []
for root, dirs, files in os.walk(path):
      for file in files:
        if file.endswith('.py'):
              pyfiles.append(os.path.join(root, file))

stopWords = ['from', 'import',',','.']

importables = []

for file in pyfiles:
    with open(file) as f:
        content = f.readlines()

        for line in content:
            if "import" in line:
                for sw in stopWords:
                    line = ' '.join(line.split(sw))

                importables.append(line.strip().split(' ')[0])

importables = set(importables)

subprocess.call(f"pip freeze > {path}/requirements.txt", shell=True)

with open(path+'/requirements.txt') as req:
    modules = req.readlines()
    modules = {m.split('=')[0].lower() : m for m in modules}


notList = [''.join(i.split('_')) for i in sys.builtin_module_names]+['os']

new_requirements = []
for req_module in importables:
    try :
        new_requirements.append(modules[req_module])

    except KeyError:
        for k,v in modules.items():
            if len(req_module)>1 and req_module not in notList:
                if fuzz.partial_ratio(req_module,k) > 90:
                    new_requirements.append(modules[k])

new_requirements = [i for i in set(new_requirements)]

new_requirements

with open(path+'/requirements.txt','w') as req:
    req.write(''.join(new_requirements))

PS:在检查Fuzzylogic时,可能还有一些其他库。

If Facing the same issue as mine i.e. not on the virtual environment and wants requirements.txt for a specific project or from the selected folder(includes children) and pipreqs is not supporting.

You can use :

import os
import sys
from fuzzywuzzy import fuzz
import subprocess

path = "C:/Users/Username/Desktop/DjangoProjects/restAPItest"


files = os.listdir(path)
pyfiles = []
for root, dirs, files in os.walk(path):
      for file in files:
        if file.endswith('.py'):
              pyfiles.append(os.path.join(root, file))

stopWords = ['from', 'import',',','.']

importables = []

for file in pyfiles:
    with open(file) as f:
        content = f.readlines()

        for line in content:
            if "import" in line:
                for sw in stopWords:
                    line = ' '.join(line.split(sw))

                importables.append(line.strip().split(' ')[0])

importables = set(importables)

subprocess.call(f"pip freeze > {path}/requirements.txt", shell=True)

with open(path+'/requirements.txt') as req:
    modules = req.readlines()
    modules = {m.split('=')[0].lower() : m for m in modules}


notList = [''.join(i.split('_')) for i in sys.builtin_module_names]+['os']

new_requirements = []
for req_module in importables:
    try :
        new_requirements.append(modules[req_module])

    except KeyError:
        for k,v in modules.items():
            if len(req_module)>1 and req_module not in notList:
                if fuzz.partial_ratio(req_module,k) > 90:
                    new_requirements.append(modules[k])

new_requirements = [i for i in set(new_requirements)]

new_requirements

with open(path+'/requirements.txt','w') as req:
    req.write(''.join(new_requirements))

P.S: It may have a few additional libraries as it checks on fuzzylogic.


回答 5

Python 3的最佳方法是:

pip3 freeze > requirements.txt

对我有用

best way for Python 3 is:

pip3 freeze > requirements.txt

it worked for me…


回答 6

如果您使用的是PyCharm,则在您将项目打开或克隆到PyCharm时,它会显示警报,并要求您安装所有必需的软件包。

if you are using PyCharm, when you open or clone the project into the PyCharm it shows an alert and ask you for installing all necessary packages.


如何将所有模块加载到文件夹中?

问题:如何将所有模块加载到文件夹中?

有人可以为我提供导入整个模块目录的好方法吗?
我有这样的结构:

/Foo
    bar.py
    spam.py
    eggs.py

我尝试通过添加__init__.py和执行操作将其转换为程序包,from Foo import *但它没有达到我希望的方式。

Could someone provide me with a good way of importing a whole directory of modules?
I have a structure like this:

/Foo
    bar.py
    spam.py
    eggs.py

I tried just converting it to a package by adding __init__.py and doing from Foo import * but it didn’t work the way I had hoped.


回答 0

列出.py当前文件夹中的所有python()文件,并将它们作为__all__变量放入__init__.py

from os.path import dirname, basename, isfile, join
import glob
modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]

List all python (.py) files in the current folder and put them as __all__ variable in __init__.py

from os.path import dirname, basename, isfile, join
import glob
modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]

回答 1

__all__变量添加到__init__.py包含:

__all__ = ["bar", "spam", "eggs"]

另请参见http://docs.python.org/tutorial/modules.html

Add the __all__ Variable to __init__.py containing:

__all__ = ["bar", "spam", "eggs"]

See also http://docs.python.org/tutorial/modules.html


回答 2

2017年更新:您可能想使用它importlib

通过添加Foo目录使Foo目录成为一个包__init__.py。在其中__init__.py添加:

import bar
import eggs
import spam

由于您希望它是动态的(这可能不是一个好主意),因此,请使用list dir列出所有py文件,并使用以下内容将其导入:

import os
for module in os.listdir(os.path.dirname(__file__)):
    if module == '__init__.py' or module[-3:] != '.py':
        continue
    __import__(module[:-3], locals(), globals())
del module

然后,从您的代码中执行以下操作:

import Foo

现在,您可以使用

Foo.bar
Foo.eggs
Foo.spam

等等from Foo import *并不是一个好主意,原因有几个,其中包括名称冲突以及难以分析代码。

Update in 2017: you probably want to use importlib instead.

Make the Foo directory a package by adding an __init__.py. In that __init__.py add:

import bar
import eggs
import spam

Since you want it dynamic (which may or may not be a good idea), list all py-files with list dir and import them with something like this:

import os
for module in os.listdir(os.path.dirname(__file__)):
    if module == '__init__.py' or module[-3:] != '.py':
        continue
    __import__(module[:-3], locals(), globals())
del module

Then, from your code do this:

import Foo

You can now access the modules with

Foo.bar
Foo.eggs
Foo.spam

etc. from Foo import * is not a good idea for several reasons, including name clashes and making it hard to analyze the code.


回答 3

扩展Mihail的答案,我相信这种非骇客的方式(例如,不直接处理文件路径)如下:

  1. 在下面创建一个空__init__.py文件Foo/
  2. 执行
import pkgutil
import sys


def load_all_modules_from_dir(dirname):
    for importer, package_name, _ in pkgutil.iter_modules([dirname]):
        full_package_name = '%s.%s' % (dirname, package_name)
        if full_package_name not in sys.modules:
            module = importer.find_module(package_name
                        ).load_module(full_package_name)
            print module


load_all_modules_from_dir('Foo')

你会得到:

<module 'Foo.bar' from '/home/.../Foo/bar.pyc'>
<module 'Foo.spam' from '/home/.../Foo/spam.pyc'>

Expanding on Mihail’s answer, I believe the non-hackish way (as in, not handling the file paths directly) is the following:

  1. create an empty __init__.py file under Foo/
  2. Execute
import pkgutil
import sys


def load_all_modules_from_dir(dirname):
    for importer, package_name, _ in pkgutil.iter_modules([dirname]):
        full_package_name = '%s.%s' % (dirname, package_name)
        if full_package_name not in sys.modules:
            module = importer.find_module(package_name
                        ).load_module(full_package_name)
            print module


load_all_modules_from_dir('Foo')

You’ll get:

<module 'Foo.bar' from '/home/.../Foo/bar.pyc'>
<module 'Foo.spam' from '/home/.../Foo/spam.pyc'>

回答 4

Python,将所有文件包含在目录下:

对于只是无法使用它的新手,他们需要手牵着手。

  1. 创建一个文件夹/ home / el / foo并main.py在/ home / el / foo下创建一个文件将以下代码放在其中:

    from hellokitty import *
    spam.spamfunc()
    ham.hamfunc()
  2. 建立目录 /home/el/foo/hellokitty

  3. 使文件__init__.py/home/el/foo/hellokitty,并把这个代码有:

    __all__ = ["spam", "ham"]
  4. 让两个Python文件:spam.pyham.py/home/el/foo/hellokitty

  5. 在spam.py中定义一个函数:

    def spamfunc():
      print("Spammity spam")
  6. 在ham.py中定义一个函数:

    def hamfunc():
      print("Upgrade from baloney")
  7. 运行:

    el@apollo:/home/el/foo$ python main.py 
    spammity spam
    Upgrade from baloney

Python, include all files under a directory:

For newbies who just can’t get it to work who need their hands held.

  1. Make a folder /home/el/foo and make a file main.py under /home/el/foo Put this code in there:

    from hellokitty import *
    spam.spamfunc()
    ham.hamfunc()
    
  2. Make a directory /home/el/foo/hellokitty

  3. Make a file __init__.py under /home/el/foo/hellokitty and put this code in there:

    __all__ = ["spam", "ham"]
    
  4. Make two python files: spam.py and ham.py under /home/el/foo/hellokitty

  5. Define a function inside spam.py:

    def spamfunc():
      print("Spammity spam")
    
  6. Define a function inside ham.py:

    def hamfunc():
      print("Upgrade from baloney")
    
  7. Run it:

    el@apollo:/home/el/foo$ python main.py 
    spammity spam
    Upgrade from baloney
    

回答 5

我自己对这个问题感到厌倦,所以写了一个叫做automodinit的软件包来解决它。您可以从http://pypi.python.org/pypi/automodinit/获取

用法是这样的:

  1. automodinit软件包包括在您的setup.py依赖项中。
  2. 像这样替换所有__init__.py文件:
__all__ = [“我将被重写”]
#请勿修改上方的行或该行!
导入automodinit
automodinit.automodinit(__ name__,__file__,globals())
自动修改
#您想要的其他任何东西都可以在这里进行,它不会被修改。

而已!从现在开始,导入模块会将__all__设置为模块中.py [co]文件的列表,并且还将导入每个文件,就像您键入的一样:

for x in __all__: import x

因此,“从M import *”的效果与“ import M”完全匹配。

automodinit 很高兴从ZIP档案内部运行,因此是ZIP安全的。

尼尔

I got tired of this problem myself, so I wrote a package called automodinit to fix it. You can get it from http://pypi.python.org/pypi/automodinit/.

Usage is like this:

  1. Include the automodinit package into your setup.py dependencies.
  2. Replace all __init__.py files like this:
__all__ = ["I will get rewritten"]
# Don't modify the line above, or this line!
import automodinit
automodinit.automodinit(__name__, __file__, globals())
del automodinit
# Anything else you want can go after here, it won't get modified.

That’s it! From now on importing a module will set __all__ to a list of .py[co] files in the module and will also import each of those files as though you had typed:

for x in __all__: import x

Therefore the effect of “from M import *” matches exactly “import M”.

automodinit is happy running from inside ZIP archives and is therefore ZIP safe.

Niall


回答 6

我知道我正在更新一个很旧的帖子,我尝试使用automodinit,但是发现它的设置过程对于python3来说是坏的。因此,基于Luca的答案,我针对此问题提出了一个更简单的答案(可能不适用于.zip),因此我认为应该在此处共享它:

在以下__init__.py模块中yourpackage

#!/usr/bin/env python
import os, pkgutil
__all__ = list(module for _, module, _ in pkgutil.iter_modules([os.path.dirname(__file__)]))

在下面的另一个包中yourpackage

from yourpackage import *

然后,将装入包中放置的所有模块,并且如果您编写一个新模块,则该模块也会自动导入。当然,小心翼翼地使用这种东西会带来巨大的责任。

I know I’m updating a quite old post, and I tried using automodinit, but found out it’s setup process is broken for python3. So, based on Luca’s answer, I came up with a simpler answer – which might not work with .zip – to this issue, so I figured I should share it here:

within the __init__.py module from yourpackage:

#!/usr/bin/env python
import os, pkgutil
__all__ = list(module for _, module, _ in pkgutil.iter_modules([os.path.dirname(__file__)]))

and within another package below yourpackage:

from yourpackage import *

Then you’ll have all the modules that are placed within the package loaded, and if you write a new module, it’ll be automagically imported as well. Of course, use that kind of things with care, with great powers comes great responsibilities.


回答 7

import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
for imp, module, ispackage in pkgutil.walk_packages(path=__path__, prefix=__name__+'.'):
  __import__(module)
import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
for imp, module, ispackage in pkgutil.walk_packages(path=__path__, prefix=__name__+'.'):
  __import__(module)

回答 8

我也遇到了这个问题,这是我的解决方案:

import os

def loadImports(path):
    files = os.listdir(path)
    imps = []

    for i in range(len(files)):
        name = files[i].split('.')
        if len(name) > 1:
            if name[1] == 'py' and name[0] != '__init__':
               name = name[0]
               imps.append(name)

    file = open(path+'__init__.py','w')

    toWrite = '__all__ = '+str(imps)

    file.write(toWrite)
    file.close()

此函数创建一个名为的文件(在提供的文件夹中)__init__.py,该文件包含一个__all__变量,用于保存文件夹中的每个模块。

例如,我有一个名为的文件夹Test ,其中包含:

Foo.py
Bar.py

因此,在脚本中,我希望将模块导入其中:

loadImports('Test/')
from Test import *

这将导入所有内容,Test并且其中的__init__.py文件Test现在将包含:

__all__ = ['Foo','Bar']

I have also encountered this problem and this was my solution:

import os

def loadImports(path):
    files = os.listdir(path)
    imps = []

    for i in range(len(files)):
        name = files[i].split('.')
        if len(name) > 1:
            if name[1] == 'py' and name[0] != '__init__':
               name = name[0]
               imps.append(name)

    file = open(path+'__init__.py','w')

    toWrite = '__all__ = '+str(imps)

    file.write(toWrite)
    file.close()

This function creates a file (in the provided folder) named __init__.py, which contains an __all__ variable that holds every module in the folder.

For example, I have a folder named Test which contains:

Foo.py
Bar.py

So in the script I want the modules to be imported into I will write:

loadImports('Test/')
from Test import *

This will import everything from Test and the __init__.py file in Test will now contain:

__all__ = ['Foo','Bar']

回答 9

Anurag的示例进行了一些更正:

import os, glob

modules = glob.glob(os.path.join(os.path.dirname(__file__), "*.py"))
__all__ = [os.path.basename(f)[:-3] for f in modules if not f.endswith("__init__.py")]

Anurag’s example with a couple of corrections:

import os, glob

modules = glob.glob(os.path.join(os.path.dirname(__file__), "*.py"))
__all__ = [os.path.basename(f)[:-3] for f in modules if not f.endswith("__init__.py")]

回答 10

Anurag Uniyal的答案有建议的改进!

#!/usr/bin/python
# -*- encoding: utf-8 -*-

import os
import glob

all_list = list()
for f in glob.glob(os.path.dirname(__file__)+"/*.py"):
    if os.path.isfile(f) and not os.path.basename(f).startswith('_'):
        all_list.append(os.path.basename(f)[:-3])

__all__ = all_list  

Anurag Uniyal answer with suggested improvements!

#!/usr/bin/python
# -*- encoding: utf-8 -*-

import os
import glob

all_list = list()
for f in glob.glob(os.path.dirname(__file__)+"/*.py"):
    if os.path.isfile(f) and not os.path.basename(f).startswith('_'):
        all_list.append(os.path.basename(f)[:-3])

__all__ = all_list  

回答 11

看到您的__init__.py定义__all__。该模块-包医生说

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

唯一的解决方案是让程序包作者提供程序包的显式索引。import语句使用以下约定:如果程序包的__init__.py代码定义了一个名为的列表__all__,则将其视为遇到从包import *时应导入的模块名称的列表。发行新版本的软件包时,软件包作者有责任使此列表保持最新。如果软件包作者没有看到从软件包中导入*的用途,他们可能还会决定不支持它。例如,该文件sounds/effects/__init__.py可能包含以下代码:

__all__ = ["echo", "surround", "reverse"]

这意味着from sound.effects import *将导入声音包的三个命名子模块。

See that your __init__.py defines __all__. The modules – packages doc says

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.

The only solution is for the package author to provide an explicit index of the package. The import statement uses the following convention: if a package’s __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered. It is up to the package author to keep this list up-to-date when a new version of the package is released. Package authors may also decide not to support it, if they don’t see a use for importing * from their package. For example, the file sounds/effects/__init__.py could contain the following code:

__all__ = ["echo", "surround", "reverse"]

This would mean that from sound.effects import * would import the three named submodules of the sound package.


回答 12

这是到目前为止我发现的最好方法:

from os.path import dirname, join, isdir, abspath, basename
from glob import glob
pwd = dirname(__file__)
for x in glob(join(pwd, '*.py')):
    if not x.startswith('__'):
        __import__(basename(x)[:-3], globals(), locals())

This is the best way i’ve found so far:

from os.path import dirname, join, isdir, abspath, basename
from glob import glob
pwd = dirname(__file__)
for x in glob(join(pwd, '*.py')):
    if not x.startswith('__'):
        __import__(basename(x)[:-3], globals(), locals())

回答 13

使用importlib你要添加的唯一事情是

from importlib import import_module
from pathlib import Path

__all__ = [
    import_module(f".{f.stem}", __package__)
    for f in Path(__file__).parent.glob("*.py")
    if "__" not in f.stem
]
del import_module, Path

Using importlib the only thing you’ve got to add is

from importlib import import_module
from pathlib import Path

__all__ = [
    import_module(f".{f.stem}", __package__)
    for f in Path(__file__).parent.glob("*.py")
    if "__" not in f.stem
]
del import_module, Path

回答 14

查看标准库中的pkgutil模块。只要__init__.py目录中有文件,它就可以让您执行所需的操作。该__init__.py文件可以为空。

Look at the pkgutil module from the standard library. It will let you do exactly what you want as long as you have an __init__.py file in the directory. The __init__.py file can be empty.


回答 15

我为此创建了一个模块,该模块不依赖__init__.py(或任何其他辅助文件),仅键入以下两行:

import importdir
importdir.do("Foo", globals())

随时重用或贡献:http : //gitlab.com/aurelien-lourot/importdir

I’ve created a module for that, which doesn’t rely on __init__.py (or any other auxiliary file) and makes me type only the following two lines:

import importdir
importdir.do("Foo", globals())

Feel free to re-use or contribute: http://gitlab.com/aurelien-lourot/importdir


回答 16

只需通过importlib导入它们,然后将它们递归添加到软件包中__all__add操作是可选的)__init__.py

/Foo
    bar.py
    spam.py
    eggs.py
    __init__.py

# __init__.py
import os
import importlib
pyfile_extes = ['py', ]
__all__ = [importlib.import_module('.%s' % filename, __package__) for filename in [os.path.splitext(i)[0] for i in os.listdir(os.path.dirname(__file__)) if os.path.splitext(i)[1] in pyfile_extes] if not filename.startswith('__')]
del os, importlib, pyfile_extes

Just import them by importlib and add them to __all__ (add action is optional) in recurse in the __init__.py of package.

/Foo
    bar.py
    spam.py
    eggs.py
    __init__.py

# __init__.py
import os
import importlib
pyfile_extes = ['py', ]
__all__ = [importlib.import_module('.%s' % filename, __package__) for filename in [os.path.splitext(i)[0] for i in os.listdir(os.path.dirname(__file__)) if os.path.splitext(i)[1] in pyfile_extes] if not filename.startswith('__')]
del os, importlib, pyfile_extes

回答 17

from . import *不够好时,这是对ted答案的改进。具体而言,在__all__此方法中无需使用。

"""Import all modules that exist in the current directory."""
# Ref https://stackoverflow.com/a/60861023/
from importlib import import_module
from pathlib import Path

for f in Path(__file__).parent.glob("*.py"):
    module_name = f.stem
    if (not module_name.startswith("_")) and (module_name not in globals()):
        import_module(f".{module_name}", __package__)
    del f, module_name
del import_module, Path

请注意,这module_name not in globals()是为了避免重新导入模块(如果已导入),因为这可能会导致循环导入。

When from . import * isn’t good enough, this is an improvement over the answer by ted. Specifically, the use of __all__ is not necessary with this approach.

"""Import all modules that exist in the current directory."""
# Ref https://stackoverflow.com/a/60861023/
from importlib import import_module
from pathlib import Path

for f in Path(__file__).parent.glob("*.py"):
    module_name = f.stem
    if (not module_name.startswith("_")) and (module_name not in globals()):
        import_module(f".{module_name}", __package__)
    del f, module_name
del import_module, Path

Note that module_name not in globals() is intended to avoid reimporting the module if it’s already imported, as this can risk cyclic imports.


从父文件夹导入模块

问题:从父文件夹导入模块

我正在运行Python 2.5。

这是我的文件夹树:

ptdraft/
  nib.py
  simulations/
    life/
      life.py

(我还在__init__.py每个文件夹中,为便于阅读,在此省略)

如何nib从模块内部导入life模块?我希望无需修补sys.path就可以做到。

注意:正在运行的主模块在ptdraft文件夹中。

I am running Python 2.5.

This is my folder tree:

ptdraft/
  nib.py
  simulations/
    life/
      life.py

(I also have __init__.py in each folder, omitted here for readability)

How do I import the nib module from inside the life module? I am hoping it is possible to do without tinkering with sys.path.

Note: The main module being run is in the ptdraft folder.


回答 0

看来问题与该模块位于父目录或类似目录中无关。

您需要将包含的目录添加ptdraft到PYTHONPATH

您说过import nib与您合作,这可能意味着您将ptdraft自身(而不是其父项)添加到了PYTHONPATH中。

It seems that the problem is not related to the module being in a parent directory or anything like that.

You need to add the directory that contains ptdraft to PYTHONPATH

You said that import nib worked with you, that probably means that you added ptdraft itself (not its parent) to PYTHONPATH.


回答 1

您可以使用相对导入(python> = 2.5):

from ... import nib

(Python 2.5的新增功能)PEP 328:绝对导入和相对导入

编辑:添加了另一个点“。” 上两个包

You could use relative imports (python >= 2.5):

from ... import nib

(What’s New in Python 2.5) PEP 328: Absolute and Relative Imports

EDIT: added another dot ‘.’ to go up two packages


回答 2

相对导入(如中的from .. import mymodule)仅在包中起作用。要导入当前模块的父目录中的“ mymodule”:

import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir) 

import mymodule

编辑__file__属性并不总是给定的。os.path.abspath(__file__)我现在建议不要使用Inspect模块来检索当前文件的文件名(和路径),而不要使用它

Relative imports (as in from .. import mymodule) only work in a package. To import ‘mymodule’ that is in the parent directory of your current module:

import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir) 

import mymodule

edit: the __file__ attribute is not always given. Instead of using os.path.abspath(__file__) I now suggested using the inspect module to retrieve the filename (and path) of the current file


回答 3

对于同级软件包的导入问题,我也发表了类似的答案。你可以在这里看到它。

没有sys.path黑客的解决方案

摘要

  • 将代码包装到一个文件夹中(例如packaged_stuff
  • setup.py在使用setuptools.setup()的地方使用创建脚本。
  • 使用以下命令以可编辑状态安装软件包 pip install -e <myproject_folder>
  • 导入使用 from packaged_stuff.modulename import function_name

设定

我假设与问题中的文件夹结构相同

.
└── ptdraft
    ├── __init__.py
    ├── nib.py
    └── simulations
        ├── __init__.py
        └── life
            ├── __init__.py
            └── life.py

我将其.称为根文件夹,就我而言,它位于中C:\tmp\test_imports

脚步

1)将A添加setup.py到根文件夹

的内容setup.py可以很简单

from setuptools import setup, find_packages

setup(name='myproject', version='1.0', packages=find_packages())

基本上是“任何” setup.py都可以。这只是一个最小的工作示例。

2)使用虚拟环境

如果您熟悉虚拟环境,请激活一个,然后跳到下一步。虚拟环境的使用不是绝对必需的,但从长远来看(当您正在进行多个项目时),它们确实可以帮助您。最基本的步骤是(在根文件夹中运行)

  • 创建虚拟环境
    • python -m venv venv
  • 激活虚拟环境
    • . /venv/bin/activate(Linux)或./venv/Scripts/activate(Win)

要了解更多有关此的信息,只需在Google上搜索“ python virtualenv教程”或类似内容即可。除了创建,激活和停用之外,您可能根本不需要任何其他命令。

创建并激活虚拟环境后,控制台应在括号中提供虚拟环境的名称。

PS C:\tmp\test_imports> python -m venv venv
PS C:\tmp\test_imports> .\venv\Scripts\activate
(venv) PS C:\tmp\test_imports>

3)pip以可编辑状态安装项目

安装您的顶级包myproject使用pip。诀窍是-e在执行安装时使用标志。这样,它以可编辑状态安装,并且对.py文件所做的所有编辑将自动包含在已安装的软件包中。

在根目录中,运行

pip install -e . (注意点,它代表“当前目录”)

您还可以看到它是通过使用安装的 pip freeze

(venv) PS C:\tmp\test_imports> pip install -e .
Obtaining file:///C:/tmp/test_imports
Installing collected packages: myproject
  Running setup.py develop for myproject
Successfully installed myproject
(venv) PS C:\tmp\test_imports> pip freeze
myproject==1.0

4)通过mainfolder在每次导入之前进行导入

在此示例中,mainfolder将为ptdraft。这样的好处是您不会与其他模块名称(来自python标准库或3rd party模块)发生名称冲突。


用法示例

笔尖

def function_from_nib():
    print('I am the return value from function_from_nib!')

life.py

from ptdraft.nib import function_from_nib

if __name__ == '__main__':
    function_from_nib()

运行life.py

(venv) PS C:\tmp\test_imports> python .\ptdraft\simulations\life\life.py
I am the return value from function_from_nib!

I posted a similar answer also to the question regarding imports from sibling packages. You can see it here.

Solution without sys.path hacks

Summary

  • Wrap the code into one folder (e.g. packaged_stuff)
  • Use create setup.py script where you use setuptools.setup().
  • Pip install the package in editable state with pip install -e <myproject_folder>
  • Import using from packaged_stuff.modulename import function_name

Setup

I assume the same folder structure as in the question

.
└── ptdraft
    ├── __init__.py
    ├── nib.py
    └── simulations
        ├── __init__.py
        └── life
            ├── __init__.py
            └── life.py

I call the . the root folder, and in my case it is located in C:\tmp\test_imports.

Steps

1) Add a setup.py to the root folder

The contents of the setup.py can be simply

from setuptools import setup, find_packages

setup(name='myproject', version='1.0', packages=find_packages())

Basically “any” setup.py would work. This is just a minimal working example.

2) Use a virtual environment

If you are familiar with virtual environments, activate one, and skip to the next step. Usage of virtual environments are not absolutely required, but they will really help you out in the long run (when you have more than 1 project ongoing..). The most basic steps are (run in the root folder)

  • Create virtual env
    • python -m venv venv
  • Activate virtual env
    • . /venv/bin/activate (Linux) or ./venv/Scripts/activate (Win)

To learn more about this, just Google out “python virtualenv tutorial” or similar. You probably never need any other commands than creating, activating and deactivating.

Once you have made and activated a virtual environment, your console should give the name of the virtual environment in parenthesis

PS C:\tmp\test_imports> python -m venv venv
PS C:\tmp\test_imports> .\venv\Scripts\activate
(venv) PS C:\tmp\test_imports>

3) pip install your project in editable state

Install your top level package myproject using pip. The trick is to use the -e flag when doing the install. This way it is installed in an editable state, and all the edits made to the .py files will be automatically included in the installed package.

In the root directory, run

pip install -e . (note the dot, it stands for “current directory”)

You can also see that it is installed by using pip freeze

(venv) PS C:\tmp\test_imports> pip install -e .
Obtaining file:///C:/tmp/test_imports
Installing collected packages: myproject
  Running setup.py develop for myproject
Successfully installed myproject
(venv) PS C:\tmp\test_imports> pip freeze
myproject==1.0

4) Import by prepending mainfolder to every import

In this example, the mainfolder would be ptdraft. This has the advantage that you will not run into name collisions with other module names (from python standard library or 3rd party modules).


Example Usage

nib.py

def function_from_nib():
    print('I am the return value from function_from_nib!')

life.py

from ptdraft.nib import function_from_nib

if __name__ == '__main__':
    function_from_nib()

Running life.py

(venv) PS C:\tmp\test_imports> python .\ptdraft\simulations\life\life.py
I am the return value from function_from_nib!

回答 4

您可以在sys.path中列出的“模块搜索路径”中使用取决于OS的路径。因此您可以轻松添加父目录,如下所示

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

如果您要添加父/母目录,

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

这在python 2和3。

You can use OS depending path in “module search path” which is listed in sys.path . So you can easily add parent directory like following

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

If you want to add parent-parent directory,

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

This works both in python 2 and 3.


回答 5

如果无法将模块文件夹添加到PYTHONPATH,则可以在程序中修改sys.path列表,Python解释程序会在其中搜索要导入的模块,python文档说:

导入名为spam的模块时,解释器首先搜索具有该名称的内置模块。如果找不到,它将在变量sys.path给出的目录列表中搜索名为spam.py的文件。sys.path从以下位置初始化:

  • 包含输入脚本的目录(或当前目录)。
  • PYTHONPATH(目录名称列表,语法与shell变量PATH相同)。
  • 取决于安装的默认值。

初始化之后,Python程序可以修改sys.path。包含正在运行的脚本的目录位于搜索路径的开始,在标准库路径之前。这意味着将加载该目录中的脚本,而不是库目录中相同名称的模块。除非打算进行更换,否则这是一个错误。

知道了这一点,您可以在程序中执行以下操作:

import sys
# Add the ptdraft folder path to the sys.path list
sys.path.append('/path/to/ptdraft/')

# Now you can import your module
from ptdraft import nib
# Or just
import ptdraft

If adding your module folder to the PYTHONPATH didn’t work, You can modify the sys.path list in your program where the Python interpreter searches for the modules to import, the python documentation says:

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

  • the directory containing the input script (or the current directory).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • the installation-dependent default.

After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended.

Knowing this, you can do the following in your program:

import sys
# Add the ptdraft folder path to the sys.path list
sys.path.append('/path/to/ptdraft/')

# Now you can import your module
from ptdraft import nib
# Or just
import ptdraft

回答 6

对python 2不太了解。
在python 3中,可以按以下方式添加父文件夹:

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

…然后可以从中导入模块

Don’t know much about python 2.
In python 3, the parent folder can be added as follows:

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

…and then one is able to import modules from it


回答 7

这是一个简单的答案,因此您可以了解它的工作原理(小型和跨平台)。
它仅使用内置模块(ossysinspect),所以应该工作
在任何操作系统(OS),因为Python是专为上。

较短的答案代码-更少的行和变量

from inspect import getsourcefile
import os.path as path, sys
current_dir = path.dirname(path.abspath(getsourcefile(lambda:0)))
sys.path.insert(0, current_dir[:current_dir.rfind(path.sep)])
import my_module  # Replace "my_module" here with the module name.
sys.path.pop(0)

如果少于此行,请用替换第二行import os.path as path, sys, inspect,在(第3行)的开头
添加inspect.getsourcefile然后删除第一行。
-但是,这会导入所有模块,因此可能需要更多的时间,内存和资源。

我的答案的代码(较长版本

from inspect import getsourcefile
import os.path
import sys

current_path = os.path.abspath(getsourcefile(lambda:0))
current_dir = os.path.dirname(current_path)
parent_dir = current_dir[:current_dir.rfind(os.path.sep)]

sys.path.insert(0, parent_dir)

import my_module  # Replace "my_module" here with the module name.

它使用来自Stack Overflow答案的示例。如何获取
Python中当前执行文件的路径?
使用内置工具查找正在运行的代码的源(文件名)。

from inspect import getsourcefile  
from os.path import abspath  

接下来,无论您想在哪里找到源文件,都只需使用:

abspath(getsourcefile(lambda:0))

我的代码sys.path在的python路径列表中添加了文件路径
因为这允许Python从该文件夹导入模块。

在代码中导入模块之后, 当添加的文件夹中的模块名称与另一个 稍后在程序中导入的模块同名时,最好sys.path.pop(0)换行运行。您需要删除导入之前添加的列表项,而不是其他路径。 如果您的程序未导入其他模块,则不删除文件路径是安全的,因为 在程序结束(或重新启动Python Shell)之后,对



sys.path消失。

有关文件名变量的注释

我的答案没有使用__file__变量来获取正在运行的
代码的文件路径/文件名,因为此处的用户经常将其描述为不可靠的。您不应将其
用于其他人使用的程序中从父文件夹导入模块

一些不起作用的示例(引用 Stack Overflow问题):

• 在某些平台找不到•有时不是完整的文件路径

  • py2exe没有__file__属性,但是有一种解决方法
  • 当您从IDLE运行时,execute()没有__file__属性
  • 我得到的OS X 10.6 NameError: global name '__file__' is not defined

Here is an answer that’s simple so you can see how it works, small and cross-platform.
It only uses built-in modules (os, sys and inspect) so should work
on any operating system (OS) because Python is designed for that.

Shorter code for answer – fewer lines and variables

from inspect import getsourcefile
import os.path as path, sys
current_dir = path.dirname(path.abspath(getsourcefile(lambda:0)))
sys.path.insert(0, current_dir[:current_dir.rfind(path.sep)])
import my_module  # Replace "my_module" here with the module name.
sys.path.pop(0)

For less lines than this, replace the second line with import os.path as path, sys, inspect,
add inspect. at the start of getsourcefile (line 3) and remove the first line.
– however this imports all of the module so could need more time, memory and resources.

The code for my answer (longer version)

from inspect import getsourcefile
import os.path
import sys

current_path = os.path.abspath(getsourcefile(lambda:0))
current_dir = os.path.dirname(current_path)
parent_dir = current_dir[:current_dir.rfind(os.path.sep)]

sys.path.insert(0, parent_dir)

import my_module  # Replace "my_module" here with the module name.

It uses an example from a Stack Overflow answer How do I get the path of the current
executed file in Python?
to find the source (filename) of running code with a built-in tool.

from inspect import getsourcefile  
from os.path import abspath  

Next, wherever you want to find the source file from you just use:

abspath(getsourcefile(lambda:0))

My code adds a file path to sys.path, the python path list
because this allows Python to import modules from that folder.

After importing a module in the code, it’s a good idea to run sys.path.pop(0) on a new line
when that added folder has a module with the same name as another module that is imported
later in the program. You need to remove the list item added before the import, not other paths.
If your program doesn’t import other modules, it’s safe to not delete the file path because
after a program ends (or restarting the Python shell), any edits made to sys.path disappear.

Notes about a filename variable

My answer doesn’t use the __file__ variable to get the file path/filename of running
code because users here have often described it as unreliable. You shouldn’t use it
for importing modules from parent folder in programs used by other people.

Some examples where it doesn’t work (quote from this Stack Overflow question):

• it can’t be found on some platforms • it sometimes isn’t the full file path

  • py2exe doesn’t have a __file__ attribute, but there is a workaround
  • When you run from IDLE with execute() there is no __file__ attribute
  • OS X 10.6 where I get NameError: global name '__file__' is not defined

回答 8

这是更通用的解决方案,其中将父目录包含在sys.path中(对我有用):

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

Here is more generic solution that includes the parent directory into sys.path (works for me):

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

回答 9

我发现以下方法可用于从脚本的父目录导入包。在示例中,我想env.pyapp.db包中导入函数。

.
└── my_application
    └── alembic
        └── env.py
    └── app
        ├── __init__.py
        └── db
import os
import sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)

I found the following way works for importing a package from the script’s parent directory. In the example, I would like to import functions in env.py from app.db package.

.
└── my_application
    └── alembic
        └── env.py
    └── app
        ├── __init__.py
        └── db
import os
import sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)

回答 10

上述解决方案也很好。解决此问题的另一种方法是

如果要从顶层目录导入任何内容。然后,

from ...module_name import *

另外,如果要从父目录导入任何模块。然后,

from ..module_name import *

另外,如果要从父目录导入任何模块。然后,

from ...module_name.another_module import *

这样,您可以根据需要导入任何特定方法。

Above mentioned solutions are also fine. Another solution to this problem is

If you want to import anything from top level directory. Then,

from ...module_name import *

Also, if you want to import any module from the parent directory. Then,

from ..module_name import *

Also, if you want to import any module from the parent directory. Then,

from ...module_name.another_module import *

This way you can import any particular method if you want to.


回答 11

对我来说,访问父目录最短和最喜欢的oneliner是:

sys.path.append(os.path.dirname(os.getcwd()))

要么:

sys.path.insert(1, os.path.dirname(os.getcwd()))

os.getcwd()返回当前工作目录的名称,os.path.dirname(directory_name)返回所传递目录的目录名称。

实际上,在我看来,Python项目体系结构应采用以下方式:子目录中的任何模块都不会使用父目录中的任何模块。如果发生这种情况,则值得重新考虑项目树。

另一种方法是将父目录添加到PYTHONPATH系统环境变量。

For me the shortest and my favorite oneliner for accessing to the parent directory is:

sys.path.append(os.path.dirname(os.getcwd()))

or:

sys.path.insert(1, os.path.dirname(os.getcwd()))

os.getcwd() returns the name of the current working directory, os.path.dirname(directory_name) returns the directory name for the passed one.

Actually, in my opinion Python project architecture should be done the way where no one module from child directory will use any module from the parent directory. If something like this happens it is worth to rethink about the project tree.

Another way is to add parent directory to PYTHONPATH system environment variable.


回答 12

在Jupyter笔记本中

只要您在Jupyter Notebook中工作,这个简短的解决方案就可能有用:

%cd ..
import nib

即使没有__init__.py文件也可以使用。

我在Linux和Windows 7上使用Anaconda3对其进行了测试。

In a Jupyter Notebook

As long as you’re working in a Jupyter Notebook, this short solution might be useful:

%cd ..
import nib

It works even without an __init__.py file.

I tested it with Anaconda3 on Linux and Windows 7.


回答 13

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

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


回答 14

当不在带有__init__.py文件的打包环境中时,pathlib库(包含在> = Python 3.4中)使将父目录的路径附加到PYTHONPATH变得非常简洁直观:

import sys
from pathlib import Path
sys.path.append(str(Path('.').absolute().parent))

When not being in a package environment with __init__.py files the pathlib library (included with >= Python 3.4) makes it very concise and intuitive to append the path of the parent directory to the PYTHONPATH:

import sys
from pathlib import Path
sys.path.append(str(Path('.').absolute().parent))

回答 15

与过去的答案相同的风格-但行数较少:P

import os,sys
parentdir = os.path.dirname(__file__)
sys.path.insert(0,parentdir)

文件返回您正在工作的位置

same sort of style as the past answer – but in fewer lines :P

import os,sys
parentdir = os.path.dirname(__file__)
sys.path.insert(0,parentdir)

file returns the location you are working in


回答 16

使用库。创建一个名为nib的库,使用setup.py安装它,使其驻留在站点程序包中,您的问题将得到解决。您不必将自己制作的所有东西都塞进一个包装中。分解成碎片。

Work with libraries. Make a library called nib, install it using setup.py, let it reside in site-packages and your problems are solved. You don’t have to stuff everything you make in a single package. Break it up to pieces.


回答 17

在Linux系统中,您可以创建一个从“ life”文件夹到nib.py文件的软链接。然后,您可以像这样简单地导入它:

import nib

In a Linux system, you can create a soft link from the “life” folder to the nib.py file. Then, you can simply import it like:

import nib

ImportError:没有名为请求的模块

问题:ImportError:没有名为请求的模块

每当我尝试导入时requests,都会出现错误提示No module Named requests

import requests

我得到的错误:

File "ex2.py", line 1, in <module>
    import requests
ImportError: No module named requests

Whenever I try to import requests, I get an error saying No module Named requests.

import requests

The error I get:

File "ex2.py", line 1, in <module>
    import requests
ImportError: No module named requests

回答 0

Requests不是内置模块(默认的python安装不附带),因此您必须安装它:

OSX / Linux

如果已安装,请使用$ sudo pip install requests(或pip3 install requests用于python3) pip。如果pip已安装但不在您的路径中,则可以使用python -m pip install requests(或python3 -m pip install requests用于python3)

或者,sudo easy_install -U requests如果已easy_install安装,也可以使用。

另外,您可以使用系统软件包管理器:

对于centos:yum install python-requests 对于Ubuntu:apt-get install python-requests

视窗

如果已安装Pip.exe并将其添加到Path Environment Variable中,请使用pip install requests(或pip3 install requests用于python3) pip。如果pip已安装但不在您的路径中,则可以使用python -m pip install requests(或python3 -m pip install requests用于python3)

或者从命令提示符,使用> Path\easy_install.exe requests,这里Path是你的Python*\Scripts文件夹,如果安装它。(例如:C:\Python32\Scripts

如果您要手动将库添加到Windows计算机,则可以下载压缩的库,解压缩它,然后将其放入Lib\site-packagespython路径的文件夹中。(例如:C:\Python27\Lib\site-packages

从来源(通用)

对于任何缺少的库,通常可从https://pypi.python.org/pypi/获得该源。您可以在此处下载请求:https//pypi.python.org/pypi/requests

在Mac OS X和Windows上,下载源zip后,解压缩它,并从未python setup.py install压缩的dir 的termiminal / cmd中运行。

来源

Requests is not a built in module (does not come with the default python installation), so you will have to install it:

OSX/Linux

Use $ sudo pip install requests (or pip3 install requests for python3) if you have pip installed. If pip is installed but not in your path you can use python -m pip install requests (or python3 -m pip install requests for python3)

Alternatively you can also use sudo easy_install -U requests if you have easy_install installed.

Alternatively you can use your systems package manager:

For centos: yum install python-requests For Ubuntu: apt-get install python-requests

Windows

Use pip install requests (or pip3 install requests for python3) if you have pip installed and Pip.exe added to the Path Environment Variable. If pip is installed but not in your path you can use python -m pip install requests (or python3 -m pip install requests for python3)

Alternatively from a cmd prompt, use > Path\easy_install.exe requests, where Path is your Python*\Scripts folder, if it was installed. (For example: C:\Python32\Scripts)

If you manually want to add a library to a windows machine, you can download the compressed library, uncompress it, and then place it into the Lib\site-packages folder of your python path. (For example: C:\Python27\Lib\site-packages)

From Source (Universal)

For any missing library, the source is usually available at https://pypi.python.org/pypi/. You can download requests here: https://pypi.python.org/pypi/requests

On mac osx and windows, after downloading the source zip, uncompress it and from the termiminal/cmd run python setup.py install from the uncompressed dir.

(source)


回答 1

对我而言,您使用的是哪个版本的Python并不明显。

如果是Python 3,一个解决方案是 sudo pip3 install requests

It’s not obvious to me which version of Python you are using.

If it’s Python 3, a solution would be sudo pip3 install requests


回答 2

requests在适用于Python2的Debian / Ubuntu上安装模块:

$ sudo apt-get install python-requests

对于Python3,命令为:

$ sudo apt-get install python3-requests

To install requests module on Debian/Ubuntu for Python2:

$ sudo apt-get install python-requests

And for Python3 the command is:

$ sudo apt-get install python3-requests


回答 3

如果您使用的是Ubuntu,则需要安装 requests

运行以下命令:

pip install requests

如果遇到权限被拒绝的错误,请在命令前使用sudo:

sudo pip install requests

If you are using Ubuntu, there is need to install requests

run this command:

pip install requests

if you face permission denied error, use sudo before command:

sudo pip install requests

回答 4

这可能为时已晚,但是即使未设置pip path,也可以运行此命令。我正在Windows 10上运行Python 3.7,这是命令

py -m pip install requests

并且您还可以将“ requests”替换为任何其他已卸载的库

This may be a liittle bit too late but this command can be run even when pip path is not set. I am using Python 3.7 running on Windows 10 and this is the command

py -m pip install requests

and you can also replace ‘requests’ with any other uninstalled library


回答 5

在OSX上,该命令将取决于您安装的python的风格。

Python 2.x-默认

sudo pip install requests

Python 3.x

sudo pip3 install requests

On OSX, the command will depend on the flavour of python installation you have.

Python 2.x – Default

sudo pip install requests

Python 3.x

sudo pip3 install requests

回答 6

就我而言,请求已经安装,但需要升级。以下命令可以解决问题

$ sudo pip install requests --upgrade

In my case requests was already installed, but needed an upgrade. The following command did the trick

$ sudo pip install requests --upgrade

回答 7

在Windows打开命令行上

pip3 install requests

On Windows Open Command Line

pip3 install requests

回答 8

我遇到了同样的问题,所以我从https://pypi.python.org/pypi/requests#downloads 请求下载文件夹中将名为“ requests”的文件夹复制到“ /Library/Python/2.7/site-packages”。现在,当您使用:导入请求时,它应该可以正常工作。

I had the same issue, so I copied the folder named “requests” from https://pypi.python.org/pypi/requests#downloadsrequests download to “/Library/Python/2.7/site-packages”. Now when you use: import requests, it should work fine.


回答 9

Brew用户可以使用下面的参考,

安装请求的命令:

python3 -m pip install requests

自制软件和Python

pip是Python的软件包安装程序,您需要该软件包requests

Brew users can use reference below,

command to install requests:

python3 -m pip install requests

Homebrew and Python

pip is the package installer for Python and you need the package requests.


回答 10

向应用程序添加第三方程序包

跟随此链接 https://cloud.google.com/appengine/docs/python/tools/libraries27?hl=zh_CN#vendoring

步骤1:在项目的根目录中有一个名为appengine_config.py的文件,然后添加以下行:

从google.appengine.ext导入供应商

添加安装在“ lib”文件夹中的所有库。

vendor.add(’lib’)

步骤2:创建一个目录,并将其命名为project的根目录下的“ lib”。

步骤3:使用pip install -t lib请求

第4步:部署到App Engine。

Adding Third-party Packages to the Application

Follow this link https://cloud.google.com/appengine/docs/python/tools/libraries27?hl=en#vendoring

step1 : Have a file by named a file named appengine_config.py in the root of your project, then add these lines:

from google.appengine.ext import vendor

Add any libraries installed in the “lib” folder.

vendor.add(‘lib’)

Step 2: create a directory and name it “lib” under root directory of project.

step 3: use pip install -t lib requests

step 4 : deploy to app engine.


回答 11

尝试sudo apt-get install python-requests

这对我有用。

Try sudo apt-get install python-requests.

This worked for me.


回答 12

对于Windows,只需将路径指定为cd,然后将路径指定为python的“脚本”,然后执行命令easy_install.exe请求即可。然后尝试导入请求…

For windows just give path as cd and path to the “Scripts” of python and then execute the command easy_install.exe requests.Then try import requests…


回答 13

唯一对我有用的东西:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
pip install requests

The only thing that worked for me:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
pip install requests

回答 14

在过去的几个月中,我有几次遇到这个问题。我还没有看到针对fedora系统的好的解决方案,因此这里是另一个解决方案。我正在使用RHEL7,发现了以下内容:

如果您urllib3通过进行了安装pip,并且requests通过进行了安装yum,则即使安装了正确的软件包,也会出现问题。如果您urllib3通过yumrequests安装了,则同样适用pip。这是我为解决此问题所做的工作:

sudo pip uninstall requests
sudo pip uninstall urllib3
sudo yum remove python-urllib3
sudo yum remove python-requests

(确认已删除所有这些库)

sudo yum install python-urllib3
sudo yum install python-requests

请注意,这仅适用于运行Fedora,Redhat或CentOS的系统。

资料来源:
这个问题(在答案的评论中)。
这个 github问题。

I have had this issue a couple times in the past few months. I haven’t seen a good solution for fedora systems posted, so here’s yet another solution. I’m using RHEL7, and I discovered the following:

If you have urllib3 installed via pip, and requests installed via yum you will have issues, even if you have the correct packages installed. The same will apply if you have urllib3 installed via yum, and requests installed via pip. Here’s what I did to fix the issue:

sudo pip uninstall requests
sudo pip uninstall urllib3
sudo yum remove python-urllib3
sudo yum remove python-requests

(confirm that all those libraries have been removed)

sudo yum install python-urllib3
sudo yum install python-requests

Just be aware that this will only work for systems that are running Fedora, Redhat, or CentOS.

Sources:
This very question (in the comments to this answer).
This github issue.


回答 15

我已经安装了python2.7和python3.6

打开〜/ .bash_profile的命令行, 我发现#Setting Python 3.6的PATH,所以我将路径更改为PATH =“ / usr / local / Cellar / python / 2.7.13 / bin:$ {PATH}”,(请确保您的python2.7的路径),然后保存。这个对我有用。

I have installed python2.7 and python3.6

Open Command Line to ~/.bash_profile I find that #Setting PATH for Python 3.6 , So I change the path to PATH=”/usr/local/Cellar/python/2.7.13/bin:${PATH}” , (please make sure your python2.7’s path) ,then save. It works for me.


回答 16

如果要request在Windows上导入:

pip install request

然后beautifulsoup4用于:

pip3 install beautifulsoup4

if you want request import on windows:

pip install request

then beautifulsoup4 for:

pip3 install beautifulsoup4

回答 17

我解决了这个问题。您可以尝试这种方法。在此文件“ .bash_profile”中,添加类似alias python=/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7

I solved this problem.You can try this method. In this file ‘.bash_profile’, Add codes like alias python=/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7


回答 18

如果您将anaconda用作Python软件包管理器,请执行以下操作:

conda install -c anaconda requests

通过pip安装请求对我没有帮助。

If you are using anaconda as your python package manager, execute the following:

conda install -c anaconda requests

Installing requests through pip didn’t help me.


回答 19

您必须确保您的请求模块未安装在最新版本的python中。

使用python 3.7时,请像这样运行python文件:

python3 myfile.py

或使用以下命令进入python交互模式:

python3

是的,这对我有用。像这样运行文件:python3 file.py

You must make sure your requests module is not being installed in a more recent version of python.

When using python 3.7, run your python file like:

python3 myfile.py

or enter python interactive mode with:

python3

Yes, this works for me. Run your file like this: python3 file.py


回答 20

Python 常见安装问题

如果Homebrew在macOS上修改了路径,这些命令也很有用。

python -m pip install requests

要么

python3 -m pip install requests

并行安装多个版本的Python?

Python Common installation issues

These commands are also useful if Homebrew screws up your path on macOS.

python -m pip install requests

or

python3 -m pip install requests

Multiple versions of Python installed in parallel?


回答 21

我的答案与@ pi-k基本相同。就我而言,我的程序在本地运行,但无法在质量检查服务器上构建。(我怀疑devops阻止了该软件包的旧版本,而且我的版本肯定已经过时了)我只是决定升级所有内容

$ pip install pip-review
$ pip-review --local --interactive

My answer is basically the same as @pi-k. In my case my program worked locally but failed to build on QA servers. (I suspect devops had older versions of the package blocked and my version must have been too out-of-date) I just decided to upgrade everything

$ pip install pip-review
$ pip-review --local --interactive

回答 22

如果您使用的是anaconda 步骤1:python 步骤2:在管理员模式下打开anaconda提示 步骤3:cd < python path > 步骤4:在此位置安装软件包

If you are using anaconda step 1: where python step 2: open anaconda prompt in administrator mode step 3: cd <python path> step 4: install the package in this location


回答 23

就我而言,这表明请求Requirement已经满足。所以我用。

sudo pip3 install requests

In my case it was showing request Requirement already satisfied . so I use.

sudo pip3 install requests

回答 24

pycharm IDE中

从菜单中的文件一键设置

2-接下来进行Python解释器

3点子

4-搜索请求并安装

在终端pycharm中写入此命令

pip install requests 

并通过以下方式使用:

import requests

in pycharm IDE

1-go to setting from File in menu

2-next go on Python interpreter

3-click on pip

4- search for requests and install it

or write this order in terminal pycharm

pip install requests 

and use it by :

import requests

回答 25

我的问题是我有四个尝试使用的python不同的python库(即使我显式调用了/usr/bin/python)。一旦我从路径中删除了shell别名和另外两个python,/usr/bin/python就可以了import requests

-HTH

My problem was that I had four different python libraries that python was trying to use (even though I was explicitly calling /usr/bin/python). Once I removed a shell alias and two other pythons from my path, /usr/bin/python was able to import requests.

-HTH


回答 26

问题可能是由于一台计算机具有多个版本的Python。确保要安装所有版本的请求模块。

就我而言,我有python版本2.73.7。我通过同时安装两个版本的python解决了此问题

The issue could be because of a machine having multiple versions of Python. Make sure that you are installing Request modules in all the versions.

In my case, I had python version 2.7 and 3.7. I resolved this issue by installing with both versions of python


回答 27

试试这个,我已经安装了anaconda,在阅读了很多文章之后,我发现这是一个解决方法

import sys
print(sys.version)
print("\n \n")
print(sys.path)
sys.path.append('/usr/local/anaconda3/envs/py36/lib/python3.6/site-packages')

在python_version文件夹中提供站点包的路径。

Try this I have anaconda installed and after going through a lot of articles I found this as a fix

import sys
print(sys.version)
print("\n \n")
print(sys.path)
sys.path.append('/usr/local/anaconda3/envs/py36/lib/python3.6/site-packages')

Provide the path of site-packages inside python_version folder.


回答 28

也许您安装了多个版本的python。尝试使用其他版本(例如python3.7 xxx.py)来确定哪个版本正确。

Maybe you have multiple versions of python installed. Try different versions, such as python3.7 xxx.py, to identify which one is the right version.


回答 29

您还可以通过首先在目录中找到pip3.exe文件在Windows上使用pip安装:对我说==> cd c:\ python34 \ scripts然后运行==> pip3安装请求

you can also use pip install on windows by first locating the pip3.exe file in the directory: say for me==> cd c:\python34\scripts then run ==> pip3 install requests


如何导入给定名称的模块为字符串?

问题:如何导入给定名称的模块为字符串?

我正在编写一个以命令作为参数的Python应用程序,例如:

$ python myapp.py command1

我希望应用程序是可扩展的,也就是说,能够添加实现新命令的新模块而不必更改主应用程序源。这棵树看起来像:

myapp/
    __init__.py
    commands/
        __init__.py
        command1.py
        command2.py
    foo.py
    bar.py

因此,我希望该应用程序在运行时找到可用的命令模块并执行适当的命令模块。

Python定义了__import__函数,该函数采用一个字符串作为模块名称:

__import __(name,globals = None,locals = None,fromlist =(),level = 0)

该函数导入模块名称,可能使用给定的全局变量和局部变量来确定如何在程序包上下文中解释该名称。fromlist提供应从名称给定的模块中导入的对象或子模块的名称。

来源:https : //docs.python.org/3/library/functions.html# import

所以目前我有类似的东西:

command = sys.argv[1]
try:
    command_module = __import__("myapp.commands.%s" % command, fromlist=["myapp.commands"])
except ImportError:
    # Display error message

command_module.run()

这工作得很好,我只是想知道是否可能有一种更惯用的方式来完成我们对这段代码所做的工作。

请注意,我特别不想使用鸡蛋或延伸点。这不是一个开源项目,我不希望有“插件”。关键是简化主应用程序代码,并且每次添加新命令模块时都无需对其进行修改。

I’m writing a Python application that takes as a command as an argument, for example:

$ python myapp.py command1

I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like:

myapp/
    __init__.py
    commands/
        __init__.py
        command1.py
        command2.py
    foo.py
    bar.py

So I want the application to find the available command modules at runtime and execute the appropriate one.

Python defines an __import__ function, which takes a string for a module name:

__import__(name, globals=None, locals=None, fromlist=(), level=0)

The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The fromlist gives the names of objects or submodules that should be imported from the module given by name.

Source: https://docs.python.org/3/library/functions.html#import

So currently I have something like:

command = sys.argv[1]
try:
    command_module = __import__("myapp.commands.%s" % command, fromlist=["myapp.commands"])
except ImportError:
    # Display error message

command_module.run()

This works just fine, I’m just wondering if there is possibly a more idiomatic way to accomplish what we are doing with this code.

Note that I specifically don’t want to get in to using eggs or extension points. This is not an open-source project and I don’t expect there to be “plugins”. The point is to simplify the main application code and remove the need to modify it each time a new command module is added.


回答 0

使用2.7 / 3.1之前的Python,这就是您要做的事情。

对于较新的版本,看到importlib.import_modulePython的2和和Python 3中

您也可以使用exec

或者,__import__您可以通过执行以下操作导入模块列表:

>>> moduleNames = ['sys', 'os', 're', 'unittest'] 
>>> moduleNames
['sys', 'os', 're', 'unittest']
>>> modules = map(__import__, moduleNames)

直接从Dive Into Python翻录。

With Python older than 2.7/3.1, that’s pretty much how you do it.

For newer versions, see importlib.import_module for Python 2 and and Python 3.

You can use exec if you want to as well.

Or using __import__ you can import a list of modules by doing this:

>>> moduleNames = ['sys', 'os', 're', 'unittest'] 
>>> moduleNames
['sys', 'os', 're', 'unittest']
>>> modules = map(__import__, moduleNames)

Ripped straight from Dive Into Python.


回答 1

对于Python 2.7和3.1及更高版本,推荐的方法是使用importlib模块:

importlib.import_module(名称,包=无)

导入模块。name参数以绝对或相对方式指定要导入的模块(例如pkg.mod或..mod)。如果使用相对术语指定名称,则必须将package参数设置为充当解析包名称的定位符的包的名称(例如import_module(’.. mod’,’pkg.subpkg’)将导入pkg.mod)。

例如

my_module = importlib.import_module('os.path')

The recommended way for Python 2.7 and 3.1 and later is to use importlib module:

importlib.import_module(name, package=None)

Import a module. The name argument specifies what module to import in absolute or relative terms (e.g. either pkg.mod or ..mod). If the name is specified in relative terms, then the package argument must be set to the name of the package which is to act as the anchor for resolving the package name (e.g. import_module(‘..mod’, ‘pkg.subpkg’) will import pkg.mod).

e.g.

my_module = importlib.import_module('os.path')

回答 2

注意:自Python 3.4以来不推荐使用imp,而建议使用importlib

如前所述,imp模块为您提供了加载功能:

imp.load_source(name, path)
imp.load_compiled(name, path)

我以前用这些来执行类似的操作。

在我的情况下,我使用所需的定义方法定义了一个特定的类。加载模块后,我将检查该类是否在模块中,然后创建该类的实例,如下所示:

import imp
import os

def load_from_file(filepath):
    class_inst = None
    expected_class = 'MyClass'

    mod_name,file_ext = os.path.splitext(os.path.split(filepath)[-1])

    if file_ext.lower() == '.py':
        py_mod = imp.load_source(mod_name, filepath)

    elif file_ext.lower() == '.pyc':
        py_mod = imp.load_compiled(mod_name, filepath)

    if hasattr(py_mod, expected_class):
        class_inst = getattr(py_mod, expected_class)()

    return class_inst

Note: imp is deprecated since Python 3.4 in favor of importlib

As mentioned the imp module provides you loading functions:

imp.load_source(name, path)
imp.load_compiled(name, path)

I’ve used these before to perform something similar.

In my case I defined a specific class with defined methods that were required. Once I loaded the module I would check if the class was in the module, and then create an instance of that class, something like this:

import imp
import os

def load_from_file(filepath):
    class_inst = None
    expected_class = 'MyClass'

    mod_name,file_ext = os.path.splitext(os.path.split(filepath)[-1])

    if file_ext.lower() == '.py':
        py_mod = imp.load_source(mod_name, filepath)

    elif file_ext.lower() == '.pyc':
        py_mod = imp.load_compiled(mod_name, filepath)

    if hasattr(py_mod, expected_class):
        class_inst = getattr(py_mod, expected_class)()

    return class_inst

回答 3

使用imp模块或更直接的__import__()功能。

Use the imp module, or the more direct __import__() function.


回答 4

现在,您应该使用importlib

导入源文件

文档实际上提供了一个配方,它像这样:

import sys
import importlib.util

file_path = 'pluginX.py'
module_name = 'pluginX'

spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)

# check if it's all there..
def bla(mod):
    print(dir(mod))
bla(module)

导入包裹

实际上,在当前目录下导入包(例如pluginX/__init__.py)非常简单:

import importlib

pkg = importlib.import_module('pluginX')

# check if it's all there..
def bla(mod):
    print(dir(mod))
bla(pkg)

Nowadays you should use importlib.

Import a source file

The docs actually provide a recipe for that, and it goes like:

import sys
import importlib.util

file_path = 'pluginX.py'
module_name = 'pluginX'

spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)

# check if it's all there..
def bla(mod):
    print(dir(mod))
bla(module)

Import a package

Importing a package (e.g., pluginX/__init__.py) under your current dir is actually straightforward:

import importlib

pkg = importlib.import_module('pluginX')

# check if it's all there..
def bla(mod):
    print(dir(mod))
bla(pkg)

回答 5

如果您想在本地人中使用它:

>>> mod = 'sys'
>>> locals()['my_module'] = __import__(mod)
>>> my_module.version
'2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]'

同样可以使用 globals()

If you want it in your locals:

>>> mod = 'sys'
>>> locals()['my_module'] = __import__(mod)
>>> my_module.version
'2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]'

same would work with globals()


回答 6

您可以使用exec

exec("import myapp.commands.%s" % command)

You can use exec:

exec("import myapp.commands.%s" % command)

回答 7

与@monkut的解决方案类似,但在http://stamat.wordpress.com/dynamic-module-import-in-python/中描述了可重用和容错的功能:

import os
import imp

def importFromURI(uri, absl):
    mod = None
    if not absl:
        uri = os.path.normpath(os.path.join(os.path.dirname(__file__), uri))
    path, fname = os.path.split(uri)
    mname, ext = os.path.splitext(fname)

    if os.path.exists(os.path.join(path,mname)+'.pyc'):
        try:
            return imp.load_compiled(mname, uri)
        except:
            pass
    if os.path.exists(os.path.join(path,mname)+'.py'):
        try:
            return imp.load_source(mname, uri)
        except:
            pass

    return mod

Similar as @monkut ‘s solution but reusable and error tolerant described here http://stamat.wordpress.com/dynamic-module-import-in-python/:

import os
import imp

def importFromURI(uri, absl):
    mod = None
    if not absl:
        uri = os.path.normpath(os.path.join(os.path.dirname(__file__), uri))
    path, fname = os.path.split(uri)
    mname, ext = os.path.splitext(fname)

    if os.path.exists(os.path.join(path,mname)+'.pyc'):
        try:
            return imp.load_compiled(mname, uri)
        except:
            pass
    if os.path.exists(os.path.join(path,mname)+'.py'):
        try:
            return imp.load_source(mname, uri)
        except:
            pass

    return mod

回答 8

以下内容对我有用:

>>>import imp; 
>>>fp, pathname, description = imp.find_module("/home/test_module"); 
>>>test_module = imp.load_module("test_module", fp, pathname, description);
>>>print test_module.print_hello();

如果要导入shell脚本:

python -c '<above entire code in one line>'

The below piece worked for me:

>>>import imp; 
>>>fp, pathname, description = imp.find_module("/home/test_module"); 
>>>test_module = imp.load_module("test_module", fp, pathname, description);
>>>print test_module.print_hello();

if you want to import in shell-script:

python -c '<above entire code in one line>'

回答 9

例如,我的模块名称类似于jan_module/ feb_module/ mar_module

month = 'feb'
exec 'from %s_module import *'%(month)

For example, my module names are like jan_module/feb_module/mar_module.

month = 'feb'
exec 'from %s_module import *'%(month)

回答 10

以下为我工作:

import sys, glob
sys.path.append('/home/marc/python/importtest/modus')
fl = glob.glob('modus/*.py')
modulist = []
adapters=[]
for i in range(len(fl)):
    fl[i] = fl[i].split('/')[1]
    fl[i] = fl[i][0:(len(fl[i])-3)]
    modulist.append(getattr(__import__(fl[i]),fl[i]))
    adapters.append(modulist[i]())

它从文件夹“ modus”加载模块。模块具有与模块名称相同名称的单个类。例如,文件modus / modu1.py包含:

class modu1():
    def __init__(self):
        self.x=1
        print self.x

结果是动态加载的类“适配器”的列表。

The following worked for me:

import sys, glob
sys.path.append('/home/marc/python/importtest/modus')
fl = glob.glob('modus/*.py')
modulist = []
adapters=[]
for i in range(len(fl)):
    fl[i] = fl[i].split('/')[1]
    fl[i] = fl[i][0:(len(fl[i])-3)]
    modulist.append(getattr(__import__(fl[i]),fl[i]))
    adapters.append(modulist[i]())

It loads modules from the folder ‘modus’. The modules have a single class with the same name as the module name. E.g. the file modus/modu1.py contains:

class modu1():
    def __init__(self):
        self.x=1
        print self.x

The result is a list of dynamically loaded classes “adapters”.