【问题标题】:Environment variable not accessible with Python with sudo [duplicate]使用 sudo 的 Python 无法访问环境变量 [重复]
【发布时间】:2016-07-14 10:16:06
【问题描述】:

我的 python 脚本有问题

首先,我定义了一个环境变量为

export TEST=test

我的 Python 脚本很简单“test.py”

import os
print os.environ['TEST']

所以当我用

运行它时
~ $ python test.py

我已经打印出预期的结果test。但是,如果我用

运行脚本
~ $ sudo python test.py

我遇到了KeyError: 'TEST' 错误。

我错过了什么?

【问题讨论】:

    标签: python linux debian environment-variables


    【解决方案1】:

    Sudo 在不同的环境下运行。 要保持当前环境使用-E 标志。

    sudo -E python test.py
    
     -E, --preserve-env
                 Indicates to the security policy that the user wishes to preserve their existing environment variables.  The security policy may return an error if the user does not have permission to
                 preserve the environment.
    

    【讨论】:

    • 太棒了!你能开发一点吗,我是Debian的新手......
    • 这对我有用。
    猜你喜欢
    • 2011-12-26
    • 2023-03-15
    • 2020-06-16
    • 2010-11-07
    • 2015-09-08
    • 1970-01-01
    • 2021-04-23
    • 2014-05-06
    • 2014-02-11
    相关资源
    最近更新 更多