Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Platform independent way to modify PATH environment variable

Is there a way to modify the PATH environment variable in a platform independent way using python?

Something similar to os.path.join()?

like image 687
resi Avatar asked Nov 05 '09 15:11

resi


People also ask

Can you design your own environment variable in Python?

To set and get environment variables in Python you can just use the os module: import os # Set environment variables os. environ['API_USER'] = 'username' os. environ['API_PASSWORD'] = 'secret' # Get environment variables USER = os.

How do I edit Environment Variables?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable.

How to create two environment variables in Python?

Under System variables go to Path →Click on “ Edit ” →add “ New ” →paste both the path copied by creating two new environment variable. 5. To ensure everything is done properly, go to “ Command Prompt ” and type python.

What is the platform dependent way to set Python Path?

The platform dependent way to set your Python Path. One platform dependent way that you may configure your Python Path is by setting the PYTHONPATH environment variable through a script file targeted at the native command-line interpreter that is provided by the Operating System where your Python application will run on.

How to create path variables in Python?

Under System variables go to Path →Click on “ Edit ” →add “ New ” →paste both the path copied by creating two new environment variable. 5. To ensure everything is done properly, go to “ Command Prompt ” and type python. If the programs starts running python (as below) then kudos you have successfully created path variable.

What is the use of pythonpath in Python?

PYTHONPATH Environment Variable in Python. Python’s behavior is greatly influenced by its environment variables. One of those variables is PYTHONPATH. It is used to set the path for the user-defined modules so that it can be directly imported into a Python program. It is also responsible for handling the default search path for Python Modules.


1 Answers

You should be able to modify os.environ.

Since os.pathsep is the character to separate different paths, you should use this to append each new path:

os.environ["PATH"] += os.pathsep + path 

or, if there are several paths to add in a list:

os.environ["PATH"] += os.pathsep + os.pathsep.join(pathlist) 

As you mentioned, os.path.join can also be used for each individual path you have to append in the case you have to construct them from separate parts.

like image 170
RedGlyph Avatar answered Sep 18 '22 22:09

RedGlyph