Removing path from Python search module path

前端 未结 3 1018
无人及你
无人及你 2020-12-08 14:24

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 Wi
相关标签:
3条回答
  • 2020-12-08 14:38

    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.

    0 讨论(0)
  • 2020-12-08 14:41

    Use

    sys.path.append('path/to/file')
    

    instead of

    sys.path.append('path/to/file/')
    

    Same with sys.path.remove().

    0 讨论(0)
  • 2020-12-08 14:52

    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
    >>> ['']
    >>>
    
    0 讨论(0)
提交回复
热议问题