简体   繁体   English

为什么 PyCharm 将当前文件和父目录添加到路径?

[英]Why PyCharm adds current file and parent directory to path?

I'm using PyCharm on Windows 10 with Python 3.8.我在带有 Python 3.8 的 Windows 10 上使用 PyCharm。 I was trying to get Python imports working from a parent directory using:我试图使用以下方法从父目录中获取 Python 导入:

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.它工作正常,但后来我注意到注释掉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.我从终端检查了这个,并按预期注释掉sys.path.append("..")破坏了程序。

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.然后我对print(sys.path)的输出和 PyCharm 的输出进行了文本比较,包括当前文件和项目目录,而从终端运行时的输出则没有。

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?从我第一次运行sys.path.append("..") ,PyCharm 是否缓存了扩展路径,或者无论如何添加它是 PyCharm 的某种默认行为? 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 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 总是将“内容根”添加到我的 PYTHONPATH,以及什么 PYTHONPATH?

Pycharm has two options which are set by default: Pycharm 有两个默认设置的选项:

Add contents root to PYTHONPATH将内容根添加到 PYTHONPATH
Add source root to PYTHONPATH将源根目录添加到 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?如果选项被选中,那么你会有你在这里的场景,你可以尝试取消选中该选项,如果场景仍然存在,那么你想试试这个链接:- 为什么 PyCharm 总是在我的 PYTHONPATH 中添加“内容根目录”,什么 PYTHONPATH? (from stack overflow) (来自堆栈溢出)

Main Points:-要点:-

  • Uncheck the options given above取消选中上面给出的选项
  • If the error persists then check the link above.如果错误仍然存​​在,请检查上面的链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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