简体   繁体   中英

How do I set environment variables in Pyinstaller?

I have the below ps code to generate an executable using myfile.spec:

python -O -m PyInstaller -v
[System.Environment]::SetEnvironmentVariable('USER', $arr[0])
[System.Environment]::SetEnvironmentVariable('PASSWD', $arr[1])
python -O -m PyInstaller myfile.spec --distpath ../dist --onefile -n myfile

Contents of myfile.spec:

added_files = [
    ('config.yaml', '.')
]

a = Analysis(['myfile.py'],
             pathex=['myfile'],
             datas=added_files,
             hiddenimports = [
               'pandas._libs.tslibs.np_datetime',
             ],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)

pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)

exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='myfile',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          runtime_tmpdir=None,
          console=True )

I did a print(os.environ) in myfile.py and the env vars for USER and PASSWD are not present. What's the best way to set these variables in the environment to be used by the python file?

Set the user variables manually in your PC.


Go to Environment variables by searching in the start bar or going to settings-->system--about-->advanced system settings-->environment variables then in User variables add a new variable with the value you want.


Now in your code you can get your variable value by entering os.environ.get('VariableName')

I achieved this by using a runtime hook. Just add a --runtime-hook option with the path to a.py file.

The documentation says

--runtime-hook: Path to a custom runtime hook file. A runtime hook is code that is bundled with the executable and is executed before any other code or module to set up special features of the runtime environment. This option can be used multiple times.

https://pyinstaller.org/en/stable/usage.html?highlight=runtime#cmdoption-runtime-hook

You could use a hook file like this

import os

os.environ["USER"] = <SOMETHING FROM A FILE>
os.environ["PASSWD"] = <SOMETHING FROM A FILE>

Keep in mind that saving passwords in files is a security breach. Ideally, your application should ask for a password.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM