0

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

jfs
  • 399,953
  • 195
  • 994
  • 1,670
Nitin Goel
  • 45
  • 4

2 Answers2

1

You almost certainly did not export MYKEY before invoking your shell script, so that shell script actually has no access to MYKEY and so the python script also has no access to it.

Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
1

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'.

Community
  • 1
  • 1
ryanpdwyer
  • 36
  • 4