Why is my Python 'sys.path' different for each tool I use to run my code?

心不动则不痛 提交于 2019-11-27 21:56:12

问题


I'm confused about the rules used to construct my Python sys.path. I understand that the fist entry will be "the directory containing the script that was used to invoke the Python interpreter", or an empty string if Python was invoked interactively, and that the last entires will be entries based on the installation of Python. But I'm confused about what's going on between these two sets of entries, in particular, how they relate to my PYTHONPATH.

When I (A) execute a script that prints out the entries of my sys.path using python test.py at the system command prompt in the ../scriptpath directory, I get:

/Users/Rax/Documents/Projects/scriptpath
... (my system PYTHONPATH, as configured in .bash_profile)  #(i)
/Users/Rax/Documents/Projects/scriptpath
... (system entries)

which is not the same as what I get when (B) I run import test while in ../scriptpath in the IPython shell

(empty string)
/usr/local/bin
... (my system PYTHONPATH)  #(i)
/Users/Rax/Documents/Projects/scriptpath
... (system entries)
/Library/Python/2.7/site-packages/IPython/extensions

or (C) in a Python shell

(empty string)
... (my system PYTHONPATH)  #(i)
/Users/Rax/Documents/Projects/scriptpath
... (system entries)

while, (D) when I run test.py in my IDE (PyCharm) I get either

/Users/Rax/Documents/Projects/scriptpath
... (user-added entries in the PyCharm Interpreter Paths settings)  #(i)
... (system entries)

or (E)

/Users/Rax/Documents/Projects/scriptpath
... (user-added entries in the PyCharm Interpreter Paths settings)  #(i)
/Users/Rax/Documents/Projects/scriptpath
... (system entries)

depending on whether I have an option to include the "contents root" enabled or not.

I think I understand where the (i) entries come from in each case: all are using my system PYTHONPATH, except PyCharm, which uses the "user added" paths at the end of "Paths" in "Interpreter Settings"; but I don't understand where the other entires come from (or for that matter, how PyCharm is able to ignore my system PYTHONPATH).

Why is the .. scriptpath entry sometimes repeated before and after (i)? What rules are used to add the other entries (such as /usr/local/bin in (B)?

来源:https://stackoverflow.com/questions/21236384/why-is-my-python-sys-path-different-for-each-tool-i-use-to-run-my-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!