Jason Donnald
Jason Donnald

Reputation: 2316

How to access the value of a variable in a python script when executed from another python script using system() command?

I have a python script(parent_script.py) which executes another python script(child_script.py) using system() command. In this python script there is a variable(var1) whose value I want to return to or access in the parent_script.py script. My current parent_script.py is:

def call_script():

    cmd = "/usr/local/bin/python2.7 child_script.py --arg1 arg1 --arg2 arg2"
    output_code = system(cmd)

    if output_code != 0:
        print(strerror(output_code) + ' \n')
        sys.exit(1)
    # Get the value of var1 in child_script.py


if __name__ == '__main__':

    call_script()  

My current child_script.py is:

def func1():
    # bunch of other code

    var1 = '2015' # this is the value that I want to access in parent_script.py


if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='Child Script')
    parser.add_argument('--arg1', required=True)
    parser.add_argument('--arg2', required=True)
    args = parser.parse_args()
    func1(args)  

How can I get the value of var1 returned to or accessed in parent_script.py?

Note: I know using subprocess I can execute the python script and get the value of var1 but in this case I am restricted to use system() only to execute the python script. Also the value of var1 in child_script is shown as a dummy value. Actual value is generated by the code that is above it and I haven't shown as it is not relevant.

Upvotes: 0

Views: 55

Answers (1)

zondo
zondo

Reputation: 20336

Since you are using python2.7, use execfile() instead of os.system():

sys.argv[1:] = ["--arg1", "arg1", "--arg2", "arg2"]
try:
    execfile("child_script.py")
except SystemExit as error:
    output_code = error.code
else:
    output_code = 0

Then you can use var1 normally. (This assumes that global var1 was put at the beginning of func1().)

Note, though, that execfile() does not exist in Python3.

Upvotes: 1

Related Questions