【问题标题】:accessing environment variable in python script when called from a shell script differs from running it in the shell directly从 shell 脚本调用时访问 python 脚本中的环境变量不同于直接在 shell 中运行它
【发布时间】:2015-05-16 02:23:10
【问题描述】:

我有一个调用 python 脚本的 shell 脚本

#!/bin/bash

sudo python test.py

test.py 正在访问一些环境变量

os.getenv('MYKEY')

当从 shell 脚本调用 python 脚本时,我得到None。但是,如果 test.py 直接从 shell 执行,它就可以正常工作。

请帮忙

【问题讨论】:

标签: python shell


【解决方案1】:

sudo默认不保留环境变量。

how to keep environment variables when using sudo

这是我为重现您的结果所做的。

$ export MYKEY=5
$ python test.py
5
$ sudo python test.py
None

如果您使用python test.py 而不是sudo python test.py,您的shell 脚本应该给出相同的结果。如果您仍想使用sudo,则需要使用sudo -E bash -c 'python test.py'

【讨论】:

    【解决方案2】:

    您几乎可以肯定在调用您的 shell 脚本之前没有export MYKEY,因此 shell 脚本实际上无法访问 MYKEY,因此 python 脚本也无法访问它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-02
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      相关资源
      最近更新 更多