Difference between $PATH, sys.path and os.environ

前端 未结 2 1055
误落风尘
误落风尘 2021-01-11 20:05

What is the difference between $PATH variable, sys.path and os.environ? I understand that they both serve as paths where python searches packages. But it\'d be nice to have

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-11 20:46

    This is actually more complicated than it would seem. It's unclear by the question if you understand the Linux/MacOS $PATH environment variable. Lets start there. The $PATH variable (in Python you're able to access the system environement variables from os.environ) denotes the current users $PATH variable as defined in various shell profile and environment files. It typically contains things like "/usr/bin" and other places where programs are installed. For example when you type "ls" into the system shell, the underlying system searches the $PATH for programs named "ls". So what actually gets executed is probably something like "/usr/bin/ls" I've included additional reading below.

    sys.path on the other hand is constructed by Python when the interpreter is started, based on a number of things. The first sentence in the help page is as follows. "A list of strings that specifies the search path for modules. Initialized from the environment variable $PYTHONPATH, plus an installation-dependent default." The installation-dependent portion typically defines the installation location of Python site packages. $PYTHONPATH is another environment variable (like $PATH) which can be added to facilitate the module search location and can be set the same way the system $PATH can

    Typically if you have non-installed sources (ie you have Python files that you want to run outside the site-packages directory) you typically need to manipulate sys.path either directly in your scripts or add the location to the $PYTHONPATH environment variable so the interpreter knows where to find your modules. Alternatively, you could use .pth files to manipulate the module search path as well

    This is just a basic overview, I hope you read the docs for better understanding

    Sources

    • Linux $PATH variable information
    • Python sys.path
    • Python site.py

提交回复
热议问题