导入另一个文件错误

时间:2017-03-13 13:53:21

标签: python pycharm python-packaging

我的文件夹/文件structrue是:

activity

testpkg/test/__init__.py; testpkg/test/test1.py testpkg/test/test2.py testpkg/setup.py 文件为空 testpkg/test/__init__.py文件内容:

testpkg/test/test1.py

class Test1: def __init__(self, name): self.name = name def what_is_your_name(self): print(f'My name is {self.name}') 文件内容:

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 以便它可以双向工作 - 直接(因此我可以在PyCharm中调试它或只运行test2.py)并在安装{之后{1}}包?我尝试更改该行:

python test2.py

test

(删除点)

我可以从命令行运行from .test1 import Test1 ,但是在安装之后,我的脚本&#34; test_exec&#34;给我错误:

from test1 import Test1

2 个答案:

答案 0 :(得分:2)

尝试像这样导入:from test.test1 import Test1

答案 1 :(得分:0)

基本上,你被困在python的相对导入问题中。当涉及到相对导入时,Python导入系统有点复杂。因此,必须谨慎使用相对导入(为此,尝试将这些名称赋予您的模块,这不会与标准模块/包冲突)。当您在python包中编写任何文件时,您将始终面临此问题。您将有两种情况: -

1)将文件作为模块运行

stream.of()

2)以脚本

运行文件
python -m package.module

在正常情况下,情况会很好,但是当你像你所做的那样进行相对导入,然后将文件作为脚本运行时,会导致问题,因为相对导入是针对# cd package python module.py 模块变量解决的,这将是在脚本的情况下__name__,因此,它将在解决相对导入时遇到问题。

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

相关问题