简体   繁体   中英

accessing environment variable in python script when called from a shell script differs from running it in the shell directly

I have a shell script which is calling the python script

#!/bin/bash

sudo python test.py

test.py is accessing some environment variable

os.getenv('MYKEY')

I get None when python script is being called from shell script. However it works fine if test.py is executed directly from the shell.

Please help

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

sudo does not keep environment variables by default.

See how to keep environment variables when using sudo .

Here is what I did to reproduce your result.

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

Your shell script should give the same result if you use python test.py rather than sudo python test.py . If you still want to use sudo , then you would need to use sudo -E bash -c 'python test.py' .

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