Python: Platform Independent Way to Modify Path Environment Variable

Python: Platform independent way to modify PATH environment variable

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.

how do I modify the system path variable in python script?

You shouldn't need to set the PATH from within the python script.
Instead, put something like

USER=joe
HOME=/home/joe
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/some/other/path
PYTHONPATH=/home/joe/pybin
MAILTO=joe
LANG=en_US.UTF-8

#min hr day mon dow
*/5 12 * * * reminder.py 'Eat lunch'

at the top of your crontab. These environment variables will then be available to all cron jobs run through your crontab.

Modify `PATH` environment variable globally and permanently using Python

As far as I know, distutils has no cross-platform utility for permanently changing environment variables. So you will have to write platform specific code.

In Windows, environment variables are stored in the registry. This is a sample code to read and set some of it's keys. I use only the standard librarie (no need to install pywin32!) to achieve that.

import _winreg as winreg
import ctypes

ENV_HTTP_PROXY = u'http://87.254.212.121:8080'

class Registry(object):
def __init__(self, key_location, key_path):
self.reg_key = winreg.OpenKey(key_location, key_path, 0, winreg.KEY_ALL_ACCESS)

def set_key(self, name, value):
try:
_, reg_type = winreg.QueryValueEx(self.reg_key, name)
except WindowsError:
# If the value does not exists yet, we (guess) use a string as the
# reg_type
reg_type = winreg.REG_SZ
winreg.SetValueEx(self.reg_key, name, 0, reg_type, value)

def delete_key(self, name):
try:
winreg.DeleteValue(self.reg_key, name)
except WindowsError:
# Ignores if the key value doesn't exists
pass

class EnvironmentVariables(Registry):
"""
Configures the HTTP_PROXY environment variable, it's used by the PIP proxy
"""

def __init__(self):
super(EnvironmentVariables, self).__init__(winreg.HKEY_LOCAL_MACHINE,
r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment')

def on(self):
self.set_key('HTTP_PROXY', ENV_HTTP_PROXY)
self.refresh()

def off(self):
self.delete_key('HTTP_PROXY')
self.refresh()

def refresh(self):
HWND_BROADCAST = 0xFFFF
WM_SETTINGCHANGE = 0x1A

SMTO_ABORTIFHUNG = 0x0002

result = ctypes.c_long()
SendMessageTimeoutW = ctypes.windll.user32.SendMessageTimeoutW
SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0, u'Environment', SMTO_ABORTIFHUNG, 5000, ctypes.byref(result));

This is just a sample code for you to get started with, it only implements settings and deleting keys.

Make sure that you always calls the refresh method after changing a registry. This will tell Windows that something has changed and it will refresh the registry settings.

Here is the link for the full application that I wrote, its a proxy switcher for Windows:
https://bitbucket.org/canassa/switch-proxy/

Add in $PATH for linux environment using python script

You can use os.environ["PATH"].

Check this question to get ideas.

Platform-independent file paths?

You can use os.path and its functions, which take care of OS-specific paths:

>>> import os
>>> os.path.join('app', 'subdir', 'dir', 'filename.foo')
'app/subdir/dir/filename.foo'

On Windows, it should print out with backslashes.

How to get the PATH environment-variable separator in Python?

os.pathsep

how to get PATH environment variable separator in nodejs?

var path      = require('path');
var delimiter = path.delimiter;

See also here.



Related Topics



Leave a reply



Submit