简体   繁体   English

如何设置“系统级”环境变量?

[英]How to set a 'system level' environment variable?

I'm trying to generate an encryption key for a file and then save it for use next time the script runs. 我正在尝试为文件生成加密密钥,然后将其保存以供脚本下次运行时使用。 I know that's not very secure, but it's just an interim solution for keeping a password out of a git repo. 我知道这不是很安全,但这只是将密码保留在git repo中的一种临时解决方案。

subprocess.call('export KEY="password"', shell=True) returns 0 and does nothing. subprocess.call('export KEY="password"', shell=True)返回0 ,但不执行任何操作。 Running export KEY="password" manually in my bash prompt works fine on Ubuntu. 在我的bash提示符中手动运行export KEY="password"可以在Ubuntu上正常工作。

subprocess.call('export KEY="password"', shell=True)

creates a shell, sets your KEY and exits: accomplishes nothing. 创建一个shell,设置您的KEY并退出:什么也不做。

Environment variables do not propagate to parent process, only to child processes. 环境变量不会传播到父进程,而只会传播到子进程。 When you set the variable in your bash prompt, it is effective for all the subprocesses (but not outside the bash prompt, for a quick parallel) 在bash提示符中设置变量时,该变量对所有子进程均有效(但在bash提示符之外,对于快速并行而言无效)

The only way to make it using python would be to set the password using a master python script (using os.putenv("KEY","password") or os.environ["KEY"]="password" ) which calls sub-modules or processes. 使用python的唯一方法是使用主python脚本(使用os.putenv("KEY","password")os.environ["KEY"]="password" )设置密码,该脚本会调用sub -模块或进程。

This isn't a thing you can do. 这不是您可以做的事情。 Your subprocess call creates a subshell and sets the env var there, but doesn't affect the current process, let alone the calling shell. 您的子进程调用将创建一个子shell并在其中设置env var,但不会影响当前进程,更不用说调用shell了。

Using Python: 使用Python:

#SET:
os.environ["EnvVar"] = "1"

#GET:
print os.environ["EnvVar"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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