Sys.path vs $ PATH

I would like to access the $ PATH variable from within a python program. So far, I understand that sys.path provides a Python module search path, but I want the PATH environment variable to be $ PATH. Is there a way to access this from within Python?

To give a little more background, I eventually want to find out where the user has Package_X / installed, so I can find the absolute path to the html file in Package_X /. If this is bad practice or if there is a better way to do this, I will be grateful for any suggestions. Thanks!

+5
source share
2 answers

you can read environment variables accessing the os.environ dictionary

 import os my_path = os.environ['PATH'] 

about finding where the package is installed depends on whether it is installed in PATH

+3
source

To check if a module is installed, you can simply try to import it:

 try: import someModule except ImportError, e: pass # not installed 

To check your path after importing it, you can access the __path__ attribute via someModule.__path__ :

Packages support another special __path__ attribute. This is initialized as a list containing the name of the directory containing the __init__.py packages before the code in this file is executed.

Regarding access to environment variables from Python , you can do the following:

 import os os.environ['PATH'] 
0
source

Source: https://habr.com/ru/post/1200494/


All Articles