简体   繁体   中英

Why PyCharm adds current file and parent directory to path?

I'm using PyCharm on Windows 10 with Python 3.8. I was trying to get Python imports working from a parent directory using:

import sys
sys.path.append("..")  # Adds higher directory to python modules path.
from trace_recursion import trace

It worked fine, but then I noticed that commenting out sys.path.append("..") # Adds higher directory to python modules path. also worked.

I checked this out running from a terminal, and commenting out sys.path.append("..") broke the program, as expected.

I then did a text comparison of the output of print(sys.path) and the output from PyCharm includes the current file and the project directory, whereas the output when run from a terminal does not.

What is going on here please? Has PyCharm cached the extended path from the first time I ran sys.path.append("..") , or is it some kind of default behavior of PyCharm to add that anyway? Or something else?

It's caused by these two options, that are by default selected in every run configuration:

Add contents root to PYTHONPATH  
Add source root to PYTHONPATH

https://www.jetbrains.com/help/pycharm/creating-and-editing-run-debug-configurations.html#createExplicitly

If unchecking those doesn't help, then the issue is most likely the same as here: Why does PyCharm always add "contents root" to my PYTHONPATH, and what PYTHONPATH?

Pycharm has two options which are set by default:

Add contents root to PYTHONPATH
Add source root to PYTHONPATH

If the options are checked then you would have the scenario you had here, you can try unchecking the option and if the scenario persists then you would like to try out this link:- Why does PyCharm always add “contents root” to my PYTHONPATH, and what PYTHONPATH? (from stack overflow)

Main Points:-

  • Uncheck the options given above
  • If the error persists then check the link above.

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