我想从同一目录中的另一个文件导入一个函数。

通常,以下工作之一:

from .mymodule import myfunction
from mymodule import myfunction

…但另一个给了我一个错误:

ImportError: attempted relative import with no known parent package
ModuleNotFoundError: No module named 'mymodule'
SystemError: Parent module '' not loaded, cannot perform relative import

这是为什么?


当前回答

我正在获取此ImportError:尝试在没有已知父包的情况下进行相对导入

在我的程序中,我使用当前路径中的文件导入其函数。

from .filename import function

然后我用包名修改了当前路径(Dot)。这解决了我的问题。

from package_name.filename import function

我希望上面的答案对你有所帮助。

其他回答

对于PyCharm用户:

我还收到了ImportError:尝试在没有已知父包的情况下进行相对导入,因为我正在添加。表示法来消除PyCharm解析错误。PyCharm错误地报告无法找到:

lib.thing导入函数

如果您将其更改为:

.lib.thing导入函数

它会使错误静音,但随后会出现前面提到的ImportError:尝试相对导入,但没有已知的父包。忽略PyCharm的解析器。这是错误的,代码运行良好,尽管它说了什么。

不幸的是,这个模块需要在包中有时需要作为脚本运行。知道我怎么做吗实现这一目标?

这样的布局很常见。。。

main.py
mypackage/
    __init__.py
    mymodule.py
    myothermodule.py

…有一个mymodule.py像这样。。。

#!/usr/bin/env python3

# Exported function
def as_int(a):
    return int(a)

# Test function for module  
def _test():
    assert as_int('1') == 1

if __name__ == '__main__':
    _test()

…一个肌肉热模块。。。

#!/usr/bin/env python3

from .mymodule import as_int

# Exported function
def add(a, b):
    return as_int(a) + as_int(b)

# Test function for module  
def _test():
    assert add('1', '1') == 2

if __name__ == '__main__':
    _test()

…还有一个像这样的男人。。。

#!/usr/bin/env python3

from mypackage.myothermodule import add

def main():
    print(add('1', '1'))

if __name__ == '__main__':
    main()

…当您运行main.py或mypackage/mymodule.py时,它工作得很好,但由于相对导入,mypackage/myothermodule.py失败。。。

from .mymodule import as_int

你应该用的方式是。。。

python3 -m mypackage.myothermodule

……但它有些冗长,与#/usr/bin/env python3。

对于这种情况,最简单的解决方法是避免使用相对导入,而只使用。。。

from mymodule import as_int

…虽然,如果它不是唯一的,或者您的包结构更复杂,您需要在PYTHONPATH中包含包含您的包目录的目录,并这样做。。。

from mypackage.mymodule import as_int

…或者如果你想让它“开箱即用”,你可以先用这个。。。

import sys
import os

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(SCRIPT_DIR))

from mypackage.mymodule import as_int

这是一种痛苦,但有一个线索,为什么在一封由某个Guido van Rossum写的电子邮件中。。。

我对这件事和任何其他提议的无聊事都持反对态度__机械唯一的用例似乎是运行发生的脚本生活在模块的目录中,我一直认为反模式。要让我改变主意,你必须说服我它不是。

在包中运行脚本是否是反模式是主观的,但就我个人而言,我发现它在包含一些自定义wxPython小部件的包中非常有用,因此我可以为任何源文件运行脚本,以显示仅包含该小部件的wx.Frame,用于测试目的。

如果以下导入:

from . import something 

不适用于您,这是因为这是python打包导入,不会与您的常规实现一起使用,下面是一个示例来演示如何使用它:

文件夹结构:

.
└── funniest
    ├── funniest
    │   ├── __init__.py
    │   └── text.py
    ├── main.py
    └── setup.py 

内部__init__.py添加:

def available_module(): 
    return "hello world"

text.py添加:

from . import available_module

在setup.py中添加

from setuptools import setup

setup(name='funniest',
  version='0.1',
  description='The funniest joke in the world',
  url='http://github.com/storborg/funniest',
  author='Flying Circus',
  author_email='flyingcircus@example.com',
  license='MIT',
  packages=['funniest'],
  zip_safe=False)

现在,这是安装软件包最重要的部分:

pip install .

在我们的系统中使用相同Python的任何地方,我们现在都可以这样做:

>> import funnies.text as fun
>> fun.available_module() 

这应该输出“hello world”

您可以在main.py中测试它(这不需要安装任何软件包)

这也是main.py

import funniest.text as fun 
print(fun.available_module())

我在使用Django时经常遇到这种情况,因为很多功能都是从manage.py脚本执行的,但我也想让我的一些模块也可以直接作为脚本运行(理想情况下,你可以让它们成为manage.py指令,但我们还没有)。

这是这样一个项目可能看起来的模型;

├── dj_app
│   ├── models.py
│   ├── ops
│   │   ├── bar.py
│   │   └── foo.py
│   ├── script.py
│   ├── tests.py
│   ├── utils.py
│   └── views.py
└── manage.py

这里的重要部分是manage.py、dj_app/script.py和dj_app/tests.py。我们还有子模块dj_app/ops/bar.py和dj_app/ops/foo.py,它们包含了我们希望在整个项目中使用的更多项目。

问题的根源通常是希望您的dj_app/script.py脚本方法在dj_app/tests.py中包含测试用例,当您运行manage.py测试时会调用这些测试用例。

这是我如何设置项目及其导入的;

# dj_app/ops/foo.py
# Foo operation methods and classes
foo_val = "foo123"

.

# dj_app/ops/bar.py
# Bar operations methods and classes
bar_val = "bar123"

.

# dj_app/script.py
# script to run app methods from CLI

# if run directly from command line
if __name__ == '__main__':
    from ops.bar import bar_val
    from ops.foo import foo_val

# otherwise
else:
    from .ops.bar import bar_val
    from .ops.foo import foo_val

def script_method1():
    print("this is script_method1")
    print("bar_val: {}".format(bar_val))
    print("foo_val: {}".format(foo_val))


if __name__ == '__main__':
    print("running from the script")
    script_method1()

.

# dj_app/tests.py
# test cases for the app
# do not run this directly from CLI or the imports will break
from .script import script_method1
from .ops.bar import bar_val
from .ops.foo import foo_val 

def main():
    print("Running the test case")
    print("testing script method")
    script_method1()

if __name__ == '__main__':
    print("running tests from command line")
    main()

.

# manage.py
# just run the test cases for this example
import dj_app.tests
dj_app.tests.main()

.

从manage.py运行测试用例;

$ python3 manage.py
Running the test case
testing script method
this is script_method1
bar_val: bar123
foo_val: foo123

自行运行脚本;

$ python3 dj_app/script.py
running from the script
this is script_method1
bar_val: bar123
foo_val: foo123

请注意,如果尝试直接运行test.py,则会出现错误,因此不要这样做;

$ python3 dj_app/tests.py
Traceback (most recent call last):
  File "dj_app/tests.py", line 5, in <module>
    from .script import script_method1
ModuleNotFoundError: No module named '__main__.script'; '__main__' is not a package

如果我遇到了更复杂的进口情况,我通常会执行这样的操作来破解它;

import os
import sys
THIS_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, THIS_DIR)
from script import script_method1
sys.path.pop(0)

我也犯了同样的错误,我的项目结构如下

->project
  ->vendors
    ->vendors.py
  ->main.py

我试着这样打电话

from .vendors.Amazon import Amazom_Purchase

这里它抛出了一个错误,所以我只需删除第一个错误就可以修复它。从声明中

from vendors.Amazon import Amazom_Purchase

希望这有帮助。