Python submodule internal links - are they just crazy?

Apologize for the newbie question. I can not get around this, and the documents do not help!

Consider the following directory structure:

spam.py
foo     / __init__.py
          ham.py
          eggs.py

with the following code:

# __init__.py
# blank

# ham.py
print( "got ham!" )

# eggs.py
print( "got eggs, importing ham!" )
import foo.ham

Now, if I am import foo.eggsinside spam.py(!), Then the correct work happens and all the links to the modules work.

BUT

If I try to execute eggs.pydirectly, I get ImportError: No module named foo.ham! If I change the import foo.hamonly to ham, it will happen correctly, but then I can’t import foo.eggs!

, eggs? "" , , , import ! foo.ham, , !

Python? ?

+3
3

: :

~/test/kl% ls -R
.:
foo  spam.py

./foo:
eggs.py  eggs.pyc  ham.py  ham.pyc  __init__.py  __init__.pyc

:

~/test/kl% cat spam.py 
import foo.eggs

~/test/kl% cd foo/
~/test/kl/foo% cat eggs.py
print( "got eggs, importing ham!" )
import ham

spam.py foo/eggs.py:

~/test/kl% python spam.py 
got eggs, importing ham!
got ham!

, python script.py, , script.py, sys.path, . python spam.py PYTHONPATH.

~/test/kl% python foo/eggs.py
got eggs, importing ham!
got ham!

~/test/kl/foo sys.path. , eggs.py import ham. ham.py ~/test/kl/foo, sys.path, Python .

~/test/kl% cd foo
~/test/kl/foo% python eggs.py
got eggs, importing ham!
got ham!

~/test/kl PYTHONPATH.

+1

foo python:

$ ls foo
eggs.py  ham.py  ham.pyc  __init__.py  __init__.pyc
$ python foo/ham.py
got ham!
$ python foo/eggs.py
got eggs, importing ham!
Traceback (most recent call last):
  File "foo/eggs.py", line 2, in <module>
    import foo.ham
ImportError: No module named foo.ham
$ PYTHONPATH=. python foo/eggs.py
got eggs, importing ham!
got ham!
+1

Python. , $PYTHONPATH. , - . ... - , .

0

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


All Articles