Removing path from Python search module path

2020-02-02 18:57发布

I understand that sys.path refers to

  1. OS paths that have your system libraries. I take it that these refer to /lib in *nix or Windows on Windows.
  2. current directory python started from - I take it if Python is started from C:\Python, this would be the current path
  3. environmental variable $PYTHONPATH or %PYTHONPATH% - This refers to the path where I can call the Python binary from the command line
  4. you can add paths at runtime - Which I understand to be when I run IDLE

I am able to add paths by running the command sys.path.append however when I run the command sys.path.remove to 'delete' the path I appended, I am unable to do so. Is there a way to do so without having to close IDLE each time?

I am running Python 2.7 on Windows 7 as well as Ubuntu

标签: python-2.7
2条回答
家丑人穷心不美
2楼-- · 2020-02-02 19:19

We can try below to insert, append or remove from sys.path

>>> import sys
>>>
>>> sys.path.insert(1, '/home/log')
>>> sys.path.append('/home/log')
>>> sys.path
['', '/home/log']
>>> sys.path.remove('/home/log')
>>> sys.path
>>> ['']
>>>
查看更多
Lonely孤独者°
3楼-- · 2020-02-02 19:22

Everything works as intended on my machine :)

Python 2.7.3 (default, Sep 26 2012, 21:51:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path.append('/home/sergey')
>>> sys.path
['', ..., '/home/sergey']
>>> sys.path.remove('/home/sergey')
>>> sys.path
['', ...]
>>> 

What exactly have you tried?

Regarding your understanding of things - I'm afraid there are some mis-understandings:

  1. sys.path is a list of directories which contain Python modules, not system libraries. So, simplifying, when you have something like import blah in your script, Python interpreter checks those directories one by one to check if there is a file called blah.py (or a subdirectory named blah with __init__.py file inside)

  2. Current directory is where the script is located, not where Python interpreter is. So if you have foo.py and bar.py in a directory, you can use import bar in foo.py and the module will be found because it's in the same directory.

  3. $PYTHONPATH is an environment variable which is getting appended to sys.path on interpreter startup. So, again, it is related to module search path and has nothing to do with starting Python from command line.

  4. Correct, you can modify sys.path at runtime - either when running a python script on in IDLE

See sys.path and site for more details.

查看更多
登录 后发表回答