简体   繁体   中英

Python in PyCharm. Import from other folder not marking folder as Sources Root

To import Python modules from other directories I've found a way to mark these directories as sources root in PyCharm. It works.
But when I run the script from command line of course command line doesn't know about sources root in PyCharm so it's neccessary to do sys.path.append for every folder where import is from.
So there is double work: in Pycharm marking directories as sources root and adding to sys.path to run as script.
Is it any way to avoid the double work? Anything that allows import modules from different directories in Pycharm and command line.

Anything that allows import modules from different directories in Pycharm and command line

You are already using virtual environments, right? If you make your code "installable" then, once it is "installed" in your virtual environment, you will be able to import it no matter in which directory you are. This is much better than tweaking "sys.path.append".

To do that you can write the setup.py file (see this link for that) and use distutils package. Another option (easier in my opinion) is to create a pyproject.toml file with poetry .

Going the "poetry route", you install poetry once and then you can just run

poetry new .  # or "poetry new mylibrary"

This initializes the project structure and creates the "pyproject.toml" file. You can now edit "pyproject.toml" as you wish. You can also add dependencies to your project with

poetry add numpy
poetry add --dev mypy
etc

Now when you run poetry install it will create a virtual environment, install the dependencies in it as well as your library. In a shell, you just need to activate the virtual environment (use poetry shell for that) and everything will work. In pycharm, you just need to set your project interpreter to the one in the virtual environment created by poetry (there is also a poetry plugin for pycharm).

There are also other tools you can use instead of the ones I mentioned, but the premise is to avoid changing sys.path and do the extra work of packaging your code. It's not really that much extra work once you learn it, and you get several advantages such as managing dependencies easily, importing from any folder, publishing your code in PyPi with a single command (if you want it), etc.

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