So I am trying to execute a file and get the returned value back using the python builtin methods available in the subprocess library.
For example, lets say I want to execute this hello_world python file:
def main(): print("in main") return("hello world!") if __name__ == '__main__': main() I do not care about getting back the statement in main. What I want to get back is the return value hello world!.
I tried numerous things but non of them worked.
Here's a list of what I tried and their outputs:
args is common for all trials: args = ['python',hello_cmd]
First trial:
p1 = subprocess.Popen(args, stdout=subprocess.PIPE) print(p1.communicate()) print("returncode is:") print(p1.returncode) output is:
(b'in main\n', None) returncode is: 0 second trial:
p2 = subprocess.check_output(args,stderr=subprocess.STDOUT) print(p2) output is:
b'in main\n' third trial:
output, result = subprocess.Popen(args, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell=False).communicate() print(output) print(result) output is:
b'in main\n' b'' fourth trial:
p4 = subprocess.run(args, stdout=PIPE, stderr=PIPE) print(p4) output is:
CompletedProcess(args=['python', '/path/to/file/hello.py'], returncode=0, stdout=b'in main\n', stderr=b'') fifth trial:
p5 =subprocess.getstatusoutput(args) print(p5) output is:
(0, '') Can anyone help?
'hello world!'to the parent process, you need to either go through a file or through stdout/stderr.hello world!, still, non of the above would work!