简体   繁体   中英

Python 3.8.x Intra and Extra Imports

When defining multiple python 3 packages in a project, I cannot determine how to configure the environment (using VS Code) such that I can run a file in any package with intra-package imports without breaking extra-package imports.

Example with absolute paths:

src/
  foo/
    a.py
    b.py
  goo/
    c.py

# b.py contents
from foo.a import *

# c.py contents
from foo.b import *

where PYTHONPATH="${workspaceFolder}\src", so it should be able to see the foo and goo directories.

I can run c.py, but running b.py gives a ModuleNotFoundError: "No module named 'foo'".

Modifying b.py to use relative paths:

# modified b.py contents
from a import *

Then allows me to run b.py, but attempting to then run c.py gives a ModuleNotFoundError: "No module named 'b'".

I have also added __init__.py files to foo/ and goo/ directories, but the errors still occurs.

I did set the cwd in the launch.json file to be the ${workspaceFolder} directory, if that is relevant.

A solution I was trying to avoid, but does work in-case there are no better solutions, is putting each individual package-dependency onto the PYTHONPATH environment variable.

Eg, "${workspaceFolder}\src;${workspaceFolder}\foo" when running c.py.

But this is not an easily scalable solution and is also something that needs to be tracked across project changes, so I do not think it is a particularly good or pythonic solution.

In fact, you can find it didn't work if you try to print the current path. It just add ".." to the path instead of the parent directory.

import sys
print(sys.path)
sys.path.append('..')
print(sys.path)

So, what we have to do is add the path of module we used to "sys" in path.

Here we have three ways:

  1. Put the written.py file into the directory that has been added to the system environment variable;
  2. Create a new.pth file under \Python\Python310\Lib\site-packages.

Write the path of the module in this new.pth file, one path per line.

  1. Using the pythonpath environment variable as upstairs said.

Then we can use this two ways to import:

sys. path. append ('a').
sys. path. insert (0, 'a')

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