简体   繁体   中英

Python intra-package references not working

I'm struggling to work with intra-package references. Here is the documentation that I'm following https://docs.python.org/3.9/tutorial/modules.html#intra-package-references

I'm doing a little test with this:

test/
    __init__.py
    module_a/
        __init__.py
        script_a.py
            ( from test.module_b import script_b )
    module_b/
        __init__.py
        script_b.py
            ( def something(): print("something") )
    

but my imports are not working and this error is arising

Exception has occurred: ModuleNotFoundError
No module named 'test'
File "/Users/nacho/Desktop/test/module_a/script_a.py", line 1, in <module>
from test.module_b import script_b

what am I doing wrong?

I'm not using any framework. just plain python 3.9 with this command

python3 script_a.py

I have not installed the test package o used the -m switch.

Regards!

It doesn't work because the package test is not found on Python's import paths . You have (at least) four options to resolve this:

  1. Run the script from the directory that contains the test directory, ie python test/module_a/script_a.py . This way all imports used within the test package must be absolute, ie of the form from test.module_b import script_b (rather than from..module_b import script_b ).
  2. Run the package via the -m switch , also from the directory containing the test directory: python -m test.module_a . You would need to provide an additional __main__.py file inside module_a that invokes the desired functionality. This way you can also use relative imports, ie . and .. .
  3. Install the whole package and then you can run it from the command line from anywhere (using the steps described in (2)).
  4. Modify PYTHONPATH to point to the directory containing test : PYTHONPATH=/path/to/test python script_a.py .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM