Is it reliable and documented how PYTHONPATH populates the sys.path?

前端 未结 1 1578
长情又很酷
长情又很酷 2021-02-13 22:58

On my machine, the values from PYTHONPATH appear to get inserted in sys.path:

  • beginning at index 1
  • order preserved
  • de-d
相关标签:
1条回答
  • 2021-02-13 23:20

    Let's go down the list.


    • beginning at index 1

    That's reliable. As stated in the PYTHONPATH docs,

    The default search path is installation dependent, but generally begins with prefix/lib/pythonversion (see PYTHONHOME above). It is always appended to PYTHONPATH.

    An additional directory will be inserted in the search path in front of PYTHONPATH as described above under Interface options. The search path can be manipulated from within a Python program as the variable sys.path.

    One directory is inserted before PYTHONPATH, which may be the current directory, the script directory, or some other directory depending on how you ran Python. Other directories are appended. The site module will also add some modules to sys.path, but site appends too:

    Importing this module will append site-specific paths to the module search path and add a few builtins...


    • order preserved

    I don't think this is explicitly documented anywhere, but search path order is important, and changing it is a backward compatibility break I don't think they would make lightly.


    • de-duplicated

    That's an undocumented effect of the site module. It won't happen if you run Python with the -S flag that disables site. You can see the code in site.removeduppaths

    0 讨论(0)
提交回复
热议问题