How do I build a non one file exe and add it to system PATH from a python script?

44 Views Asked by At

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.

1

There are 1 best solutions below

0
hecker5556 On
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