Import a module from either a single package or from an external package in Python 3

Well, the script is very simple. I have a file structure like this:

.
├── interface.py
├── pkg
│   ├── __init__.py
│   ├── mod1.py
│   ├── mod2.py

Here are my conditions:

  • mod2 you need to import mod1.
  • both interface.py and mod2 must be run independently as the main script. If you want, take the interface as an up-to-date program, and mod2 as an internal package tester.

So in Python 2, I just would have done import mod1in mod2.py, and both python2 mod2.pyand python2 interface.pywould work as expected.

However, and this is the part that I less understand using Python 3.5.2 if I do import mod1; then I can do it python3 mod2.py, but it python3 interface.pygives: ImportError: No module named 'mod1':(

, -, python 3 import pkg.mod1 . , , python3 interface.py; python3 mod2.py : ImportError: No module named 'pkg'

, : from. import mod1 from. import mod1 python3 interface.py ; mod2.py , SystemError: Parent module '' not loaded, cannot perform relative import :( :(

"", , - python -m pkg.mod2 python -m pkg.mod2. pkg ? , - , , -m? ?

. Python 2, Python 3.

: ( "") : https://gitlab.com/Akronix/test_python3_packages. , , , python2.


, :

:

+11
1

TL;DR:

  • python -m pkg.mod2.
  • from. import mod1 from. import mod1.

"", , - python -m pkg.mod2 python -m pkg.mod2.

-m "" - . ; .

" " . . .

pkg ?

- , . .

, , , . pkg, .

# inside mod1.py
# import mod2 - this is wrong! It can pull in an arbitrary mod2 module
# these are correct, they uniquely identify the module
import pkg.mod2
from pkg import mod2
from . import mod2
from .mod2 import foo  # if pkg.mod2.foo exists

, <import> as <name> . , import pkg.mod2 as mod2 .

, - , , -m? ?

, -m . , python3 -m json.tool.

echo '{"json":"obj"}' | python -m json.tool

(), PYTHONPATH . -m .

, export PYTHONPATH="$(pwd)/.." .

. Python 2, Python 3.

Python 2. , , .

, .

+3

Source: https://habr.com/ru/post/1689344/


All Articles