4

I'am trying to start an exe file (the exe file is the output of c++ project compiled with visual studio) from a python program. In the properties of this c++ project (configuration ->properties-> debugging-> environment) the following setting in the

     (PATH = %PATH%;lib\testfolder1;lib\testfolder2) 

is given.
is there any way to set path environment variable to

  1. PATH = %PATH%
  2. lib\testfolder1
  3. lib\testfolder2

in a python program?

Thanks in advance for your replay

3
  • Path is an operating system environment variable, changing it can damage temporarily (up to the next boot) the access paths of several programs or libraries. If the path modification is required only for the runtime of your program, better save a copy of the original path and then modify it additively, so it can be set to its original value before exiting the program. %PATH% means the path variable itself, which is a way in os level to set the path variable additively. Such as : If path is C:\;C:\d1, PATH=%PATH%;C:\d2 is the same as typing PATH = C:\;C:\d1;C:\d2 Commented Apr 11, 2016 at 13:50
  • 1
    thanks Lhsan for the detailed explanation. I have the misunderstood % PATH% before. now it is works Commented Apr 11, 2016 at 13:54
  • 1
    If you're starting an executable, use subprocess.Popen, or one of the high-level functions such as subprocess.check_output, and use its env option to pass a modified environment to the child. For example: environ = os.environ.copy(); environ['PATH'] += os.pathsep + os.pathsep.join([r'lib\testfolder1', r'lib\testfolder2']); p = subprocess.Popen([exepath, arg1, arg2, ...], env=environ). Commented Apr 11, 2016 at 15:06

3 Answers 3

8

You can update PATH using several methods:

import sys
sys.path += ["c:\\new\\path"]
print sys.path

or

import os
os.environ["PATH"] += os.pathsep + os.pathsep.join(["c:\\new\\path"])
print os.environ["PATH"]
Sign up to request clarification or add additional context in comments.

2 Comments

It is my understanding that sys.path relates to the Python module search path. It is not the same as the OS PATH environment variable. (In fact sys.path is associated with the PYTHONPATH environment variable.)
To add current folder in which the .py file is in to path (for example if you use ctypes and have .dll files in it): os.environ["PATH"] += os.pathsep + os.path.dirname(os.path.abspath(__file__)). You have to run this before importing via ctypes.
2

Repost Yaron's answer but dropped the sys.path. As in his post's comment, sys.path is for module search, not command search. PATH is for command search.

import os
os.environ["PATH"] += os.pathsep + os.pathsep.join(["c:\\new\\path"])
print os.environ["PATH"]

2 Comments

Your answer is correct, but I've submitted an edit to the top-voted answer in the meantime.
This affects the Python pgm only. It doesn't modify the system (DOS) PATH.
0

Here is a solution that I created. It will check to see if the path already exists, and if not then it will write it to the registry for both the the current user and machine.

I've tested that the current process will not have the updated environment, but a new command line launched from the Run command will be updated.

Note that when a new window is created that it will have the updated path values.

def AppendWindowsPath(path):
  def AddPathInRegistry(HKEY, reg_path, new_path):
    reg = None
    key = None
    try:
      reg = ConnectRegistry(None, HKEY)
      key = OpenKey(reg, reg_path, 0, KEY_ALL_ACCESS)
      path_string, type_id = QueryValueEx(key, 'PATH')
      path_list = [f.strip("\r\n") for f in  path_string.split(';') if f]

      if new_path in path_list:
        print(new_path + " is already in %PATH%")
        return "ALREADY_IN_ENVIRONMENT"

      print("Adding " + new_path + " to %PATH%")
      SetValueEx(key, 'PATH', 0, REG_EXPAND_SZ, path_string + ";" + new_path)
      return "UPDATED_PATH"
    except Exception as e:
      print("ERROR while executing registry edit with " + str(HKEY) + "/" + reg_path)
      return "ERROR"
    finally:
      if key: CloseKey(key)
      if reg: CloseKey(reg)


  # Add the path to the current machine
  result_machine = \
    AddPathInRegistry(HKEY_LOCAL_MACHINE,
                      r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment',
                      path)

  # Update the path for the current user.
  result_user = \
    AddPathInRegistry(HKEY_CURRENT_USER, r'Environment', path)

  if ("UPDATED_PATH" in result_machine) or ("UPDATED_PATH" in result_user):
    # Updates Environment.
    win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.