Python 3:如何最好地做到相对导入同时适用于pip安装的代码和直接运行py文件?

时间:2018-10-18 14:30:15

标签: python-3.x import pip executable

我经常发现自己正在编写类似以下内容的python 3相对导入:

# in main.py
try:
    # An import that works if the current module is installed with pip
    from .otherfile import some_func
    print("The .otherfile import worked")
except ImportError:
    # An import that works of I run ./main.py from my source code folder
    print("The .otherfile import failed")
    from otherfile import some_func
    print("The otherfile import worked")

此代码示例按预期工作,我可以执行以下两项操作:

[username@localhost mymodule]# python3.6 mymodule/main.py
The .otherfile import failed
The otherfile import worked
Hello World?

[username@localhost mymodule]# python3.6
Python 3.6.5 (default, Apr 10 2018, 17:08:37)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import mymodule
The .otherfile import worked
>>> mymodule.run_me()
Hello World?
>>>

我的导入函数在两种情况下都运行,但是我不禁以为我在某种程度上做错了导入。必须有一种方法可以对pip安装的代码和直接运行的代码都正确地进行简单的相对导入。

如果我只是尝试从其他文件导入some_func,那么它对于python3.6 mymodule / main.py可以正常工作,但是当我从pip安装的模块中尝试时,我得到了:

[username@localhost mymodule]# python3.6
Python 3.6.5 (default, Apr 10 2018, 17:08:37)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import mymodule
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/testuser/src/mymodule/mymodule/__init__.py", line 1, in <module>
    from .main import run_me
  File "/home/testuser/src/mymodule/mymodule/main.py", line 3, in <module>
    from otherfile import some_func
ModuleNotFoundError: No module named 'otherfile'

我将测试用例的副本放在github上; https://github.com/James00001/mymodule

重新总结问题:

进行相对的python导入(既可以直接执行文件又可以从pip安装的模块导入文件)的正确方法是什么?

0 个答案:

没有答案