导入另一个文件E

2024-09-21 02:55:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我的文件夹/文件结构是:

testpkg/test/__init__.py;
testpkg/test/test1.py
testpkg/test/test2.py
testpkg/setup.py

testpkg/test/__init__.py文件为空。
testpkg/test/test1.py文件内容:

^{pr2}$

testpkg/test/test2.py文件内容:

from .test1 import Test1


def main():
    t = Test1('me')
    t.what_is_your_name()

if __name__ == '__main__':
    main()

/testpkg/setup.py内容:

from setuptools import setup

setup(name='test',
      version='0.1',
      packages=['test'],
      entry_points={
          'console_scripts': [
              'test_exec = test.test2:main'
          ]
      }
      )

我无法直接调试/运行test2.py脚本,因为它会给我错误:

» python test/test2.py
Traceback (most recent call last):
  File "test/test2.py", line 1, in <module>
    from .test1 import Test1
ModuleNotFoundError: No module named '__main__.test1'; '__main__' is not a package

但是当我用pip install -U .安装它时

它起作用:

» pip install -U .
Processing /home/kossak/Kossak/files_common/PythonProjects/testpkg
Installing collected packages: test
  Found existing installation: test 0.1
    Uninstalling test-0.1:
      Successfully uninstalled test-0.1
  Running setup.py install for test ... done
Successfully installed test-0.1

» test_exec
My name is me

问题是:如何正确地编写test2.py,这样它就可以双向工作了——直接(这样我就可以在PyCharm中调试它,或者只使用python test2.py运行它)和在安装test包之后?我试着换行:

from .test1 import Test1

from test1 import Test1

(删除圆点)

我可以从命令行运行test2.py,但在安装之后,我的脚本“test\u exec”给了我一个错误:

Traceback (most recent call last):
  File "/home/kossak/anaconda3/bin/test_exec", line 11, in <module>
    load_entry_point('test==0.1', 'console_scripts', 'test_exec')()
  File "/home/kossak/anaconda3/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/pkg_resources/__init__.py", line 565, in load_entry_point
  File "/home/kossak/anaconda3/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/pkg_resources/__init__.py", line 2598, in load_entry_point
  File "/home/kossak/anaconda3/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/pkg_resources/__init__.py", line 2258, in load
  File "/home/kossak/anaconda3/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/pkg_resources/__init__.py", line 2264, in resolve
  File "/home/kossak/anaconda3/lib/python3.6/site-packages/test/test2.py", line 1, in <module>
    from test1 import Test1
ModuleNotFoundError: No module named 'test1'

Tags: infrompytestimporthomeinitpackages
2条回答

尝试如下导入:from test.test1 import Test1

基本上,您会陷入python的相对导入困境。Python导入系统在相对导入方面有点复杂。因此,必须谨慎地使用相对导入(为此,请尝试为您的模块指定这样的名称,这不会与标准模块/包冲突)。在python包中编写任何文件时,都会遇到这个问题。你会有两种情况:

1)将文件作为模块运行

python -m package.module

2)将文件作为脚本运行

^{pr2}$

在正常情况下,一切都会很好,但是当您像您所做的那样进行相对导入,然后以脚本形式运行file时,会导致问题,因为针对__name__模块变量解析相对导入,而对于脚本,这将是'__main__',因此,它在解决相对导入时将面临问题。在

请参阅以下文章:-http://python-notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html

相关问题 更多 >

    热门问题