how to set PATH=%PATH% as environment in Python script?

社会主义新天地 提交于 2020-01-16 04:12:20

问题


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


回答1:


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"]



回答2:


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')


来源:https://stackoverflow.com/questions/36549183/how-to-set-path-path-as-environment-in-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!