I have a code workflow in which from a main script(level 0) I call another script through subprocess
. This subprocess script
(level 1) in turn calls another script as a subprocess
. Now from this level 2 subprocess script I want to return the value of a variable upto the main script(level 0). I have tried Popen.communicate()
but I am not able to return the value. My current code is as:
main_script.py
def func():
para = ['a','b']
result = subprocess.Popen([sys.executable,"first_subprocess.py"]+para,stdout=subprocess.PIPE)
result.wait()
return_code = result.returncode
out, err = sub_result.communicate()
if return_code == 1:
return return_code
else:
if out is not None:
print 'return value: ', out
if __name__ == '__main__':
func()
From above script is called first_subprocess.py
which has:
def some_func():
# some other code and multiple print statements
para = ['a','b']
result = subprocess.Popen([sys.executable,"second_subprocess.py"]+para,stdout=subprocess.PIPE)
result.wait()
out, err = result.communicate()
return_code = sub_result.returncode
if return_code == 0:
return out
if __name__ == '__main__':
some_func()
The second_subprocess.py
returns a value like:
def test():
# some other code and multiple print statements
val = 'time'
print 'returning value'
return val
if __name__ == '__main__':
test()
When I try above code I get all the print
statements in the codes as an output but not the return value. Even if try to print
the variable value in subprocess instead of doing a return it wont serve the purpose because there are multiple print statements.
How can I return the variable value in this case?
UPDATED VERSION:
After @Anthons suggestion I have modifed my first_subprocess.py
script and main_script.py
as follows:
first_subprocess.py:
def some_func():
try:
key = None
if not (key is None):
para = ['a','b']
result = subprocess.Popen([sys.executable,"second_subprocess.py"]+para,stdout=subprocess.PIPE)
sub_result.wait()
out, err = sub_result.communicate()
return_code = sub_result.returncode
if return_code == 0:
for line in out.splitlines():
if not line.startswith('>>>'):
continue
print line
else:
sys.exit(0)
except:
return 1
Main_script.py:
if out is not None:
for line in out.splitlines():
if not line.startswith('>>>'):
continue
value = line.split(':',1)[1].lstrip()
print 'return value:',value`
When I execute above I get UnboundLocalError: local variable 'value' referenced before assignment
at the print value
command. It seems if I do not execute the code in level 1 script and do a sys.exit() then out
in main script is neither empty nor none but it has some undefined value and thus the value
variable doesn't get initialized and throws error