我正在尝试从 python 进程访问环境变量。我将其导出为export var=value
。这对于命令来说很好,pyton program.py
但对于 则不行sudo python program.py
。如果进程以 sudo 启动,如何确保进程可以访问环境变量?
答案1
的默认安全策略sudo
通常会阻止它继承环境变量。但是,除非文件中明确拒绝了特定变量sudoers
,否则您应该能够通过指定-E
sudo 选项来允许它,例如
$ VAR="value" python -c 'import os; print os.environ.get("VAR")'
value
$
$ VAR="value" sudo python -c 'import os; print os.environ.get("VAR")'
None
$
$ VAR="value" sudo -E python -c 'import os; print os.environ.get("VAR")'
value
$
看man sudo
-E The -E (preserve environment) option indicates to the
security policy that the user wishes to preserve their
existing environment variables. The security policy may
return an error if the -E option is specified and the user
does not have permission to preserve the environment.