0

OS: Mac OSX 10.14 Python 2.7

I have a python script which looks like below:

#! /usr/bin/python

import os

os.system('./binaryfileproducesenv_variables > ./env_variables_file')
os.system('chmod 744 ./env_variables_file')
os.system('./env_variables_file')

os.system('python anotherpythonscript.py')

The env_variables_file looks like this:

passwordA='abcd';
passwordB='1234';
export passwordA passwordB

The anotherpythonscript.py will only work properly if the environment variables above are set properly. When i run it via the main python script it does not define the variables. Although, if i run the ./env_variables_file directly from the command line it will set the environment variables. Any suggestions how to run this through the Python script and have it set the environment variables.

aznjonn
  • 113
  • 16
  • 1
    `os.system('python anotherpythonscript.py')` - why do you do this? Why don't you just import it as a module and run the main function (if it was designed to run as script and has `if __name__="__main__": main()`)? – h4z3 Dec 11 '19 at 17:18
  • 2
    https://stackoverflow.com/questions/5971312/how-to-set-environment-variables-in-python I think this answers your question – polololya Dec 11 '19 at 17:18
  • I was looking at using os.environment, but the env_variables_file is a newly created file that needs to be created everytime (with new environemnts passwords) we want to run the anotherpythonscript.py script – aznjonn Dec 11 '19 at 17:22
  • if you use only `os.system` in python script then you should rather create bash script. You will have the same command but without `os.system` – furas Dec 11 '19 at 18:13
  • 1
    `os.system('./env_variables_file')` doesn't do what you think it does. Running a script sets the export in the one subshell. You need to read the file, and set each variable individually using `os.environ` before calling the next script. That said: just make a bash wrapper instead of a python one, reducing complexity and execution time. – tink Dec 11 '19 at 18:26
  • Why in the world are you using python for this rather than a shell actually designed for this type of task such as bash or ksh? Also, using `os.system('some string') is the equivalent of `sh -c 'some string'` and isn't the most efficient way to do this. – Kurtis Rader Dec 12 '19 at 00:18

1 Answers1

1

See comment above:

#!/usr/bin/env bash
./binaryfileproducesenv_variables > ./env_variables_file
. ./env_variables_file
python anotherpythonscript.py
tink
  • 14,342
  • 4
  • 46
  • 50