sys.path vs. $PATH
Asked Answered
D

3

6

I would like to access the $PATH variable from inside a python program. My understanding so far is that sys.path gives the Python module search path, but what I want is $PATH the environment variable. Is there a way to access that from within Python?

To give a little more background, what I ultimately want to do is find out where a user has Package_X/ installed, so that I can find the absolute path of an html file in Package_X/. If this is a bad practice or if there is a better way to accomplish this, I would appreciate any suggestions. Thanks!

Dosh answered 16/8, 2014 at 23:9 Comment(2)
What do you mean by "package"? Is it a python module? Or a distribution package for a specific distribution? Depending on what you are looking for, there may already be existing solutions. In the most general case, $PATH is probably not very helpful.Distill
In setup.py, use data_files to install external files in a place where your Python package can find them.Phillip
S
4

you can read environment variables accessing to the os.environdictionary

import os

my_path = os.environ['PATH']

about searching where a Package is installed, it depends if is installed in PATH

Slier answered 16/8, 2014 at 23:13 Comment(0)
P
5

sys.path and PATH are two entirely different variables. The PATH environment variable specifies to your shell (or more precisely, the operating system's exec() family of system calls) where to look for binaries, whereas sys.path is a Python-internal variable which specifies where Python looks for installable modules.

The environment variable PYTHONPATH can be used to influence the value of sys.path if you set it before you start Python.

Conversely, os.environ['PATH'] can be used to examine the value of PATH from within Python (or any environment variable, really; just put its name inside the quotes instead of PATH).

Phillip answered 10/11, 2020 at 11:43 Comment(1)
Perhaps see also https://mcmap.net/q/137240/-pythonpath-vs-sys-pathPhillip
S
4

you can read environment variables accessing to the os.environdictionary

import os

my_path = os.environ['PATH']

about searching where a Package is installed, it depends if is installed in PATH

Slier answered 16/8, 2014 at 23:13 Comment(0)
N
0

To check whether a certain module is installed you can simply try importing it:

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

In order to check its path once its imported you can access its __path__ attribute via someModule.__path__:

Packages support one more special attribute, __path__. This is initialized to be a list containing the name of the directory holding the package’s __init__.py before the code in that file is executed.

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

import os
os.environ['PATH']
Nabonidus answered 16/8, 2014 at 23:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.