How do I make PyCharm use system $PYTHONPATH to add paths to the "interpreter paths" setting?

Hi,

I'm using PyCharm Community Edition 2019.2.6, on MacOS 10.14.6.

I have a folder called my_packages in which I store self-written packages that I regularly want to import into new projects. I would like every new project I create in PyCharm to include the path to this folder in its interpreter paths configuration. I can configure this manually every time I create a new project, but I'd rather not have to. In case it's relevant, I always use venvs and let PyCharm create and manage them for new projects.

I have the path to my_packages listed in my system-wide $PYTHONPATH environment variable (exported in my .bash_profile file). I would have expected that whenever PyCharm creates a new virtual environment, it would look at the system-wide $PYTHONPATH environment variable, and add any paths found in that to the local venv's interpreter paths setting. This does not appear to be happening.

As a test, I created a package in the my_packages folder called helloworld. All it does is print "hello world" when it is imported. I then created a fresh project in PyCharm, along with a new venv. As you can see from the screenshot below, when I import helloworld in the interactive window in my new project, it works.

This is because the terminal window inside PyCharm is aware of the global $PYTHONPATH variable:

However, when I write the same import helloworld in the PyCharm editor, save it as a file and run it (using the right-click, 'Run' command), it fails:

This would seem to be because the PyCharm interpreter settings for "Interpreter Paths" have not added the path given in $PYTHONPATH:

NB: I haven't screenshotted it, but running the saved Python file (the same one that fails in the editor) manually in the PyCharm terminal by typing python demo.py works - so the issue appears to be only when running the script from the editor itself with the Run command.

I know that I can add the path to my_packages to the interpreter paths setting manually, but I don't want to have to do that every time I create a new project. How can I make it so that every new project inherits $PYTHONPATH automatically?

Thanks!

2 comments
Comment actions Permalink

Try making the root folder of the Project "Sources Root"

By right clicking the folder in the tree view and choosing Mark Directory as > Sources Root

0
Comment actions Permalink

dio Thanks, appreciate the suggestion.

Is that a global PyCharm setting, or per-project? I'm looking for a way to not have to change a setting like that every time I start a new project.

0

Please sign in to leave a comment.