0

Any other answer would just add the exe to the current python session's path, and only "setx" would add it to USER path (erasing previous ones unless u save them somewhere).

I'm currently using cx_freeze, and there is an option to add to system path for the .msi builder and not the .exe builder. My goal is to have the exe be lightweight and at the same time be accessible from anywhere. I'm also planning to make it universal so it would work both on windows and linux I tried using

os.environ['PATH'] = os.environ['PATH'] += os.pathsep(directory)

But that would only edit it for that current python session.

Donald Duck
  • 8,409
  • 22
  • 75
  • 99

1 Answers1

0
import winreg
def main():
    def add_to_path(directory, user=False):
        if user:
            key = winreg.HKEY_CURRENT_USER
            subkey = 'Environment'
        else:
            key = winreg.HKEY_LOCAL_MACHINE
            subkey = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'

        with winreg.OpenKey(key, subkey, 0, winreg.KEY_ALL_ACCESS) as regkey:
            path_value, _ = winreg.QueryValueEx(regkey, 'Path')
            print(path_value)
            path_value += ';' + directory
            winreg.SetValueEx(regkey, 'Path', 0, winreg.REG_EXPAND_SZ, path_value)

    # Example usage
    directory_path = filepath
    add_to_path(directory_path)
if __name__ == '__main__':
    import subprocess
    subprocess.run('pip install pyuac'.split())
    subprocess.run('pip install pypiwin32'.split())
    #require admin to make sure modules are installed correctly
    import pyuac 

    if not pyuac.isUserAdmin():
        pyuac.runAsAdmin()
    else:
        main()

this is what seemed to work for windows, requires admin

  • You found the solution fast! can you give your resources? – ylj Aug 12 '23 at 19:53
  • @ylj i asked Clyde on discord "in python, after building a python script into an exe with dependencies in different folders, how do I add that exe into either USER PATH or SYSTEM PATH using python", then he says u need admin, so i say "but lets say i did get admin privs now what" (script from [a question on how to elevate permissions](https://stackoverflow.com/questions/19672352/how-to-run-script-with-elevated-privilege-on-windows)), i searched through the internet before Clyde and I wasnt even close at meeting winreg – hecker5556 Aug 12 '23 at 21:26