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

通常,以下工作之一:

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

这是为什么?


当前回答

太长,读不下去了通过在python脚本的入口点添加以下内容,将脚本路径附加到系统路径。

import os.path
import sys
PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))

现在,您可以在PyCharma和Terminal中运行项目了!!

其他回答

如果以下导入:

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())

为了避免这个问题,我设计了一个重新包装包装的解决方案,这对我来说已经奏效了一段时间。它将上层目录添加到lib路径:

import repackage
repackage.up()
from mypackage.mymodule import myfunction

使用智能策略(检查调用堆栈),重新打包可以在各种情况下进行相对导入。

我需要从主项目目录运行python3才能使其正常工作。

例如,如果项目具有以下结构:

project_demo/
├── main.py
├── some_package/
│   ├── __init__.py
│   └── project_configs.py
└── test/
    └── test_project_configs.py

解决方案

我将在文件夹project_demo/中运行python3,然后执行

from some_package import project_configs

如果两个包都在您的导入路径(sys.path)中,并且您想要的模块/类在example.example.py中,那么要访问该类而不进行相对导入,请尝试:

from example.example import fkt

我在使用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)