How to return string from main function?

How can I get string as return in this script?

main.py

from subprocess import Popen, PIPE
import os
import sys

child = os.path.join(os.path.dirname(__file__), "child.py")
command = [sys.executable, child, "test"]
process = Popen(command, stdout=PIPE, stdin=PIPE)
process.communicate()
print(process.poll())

child.py

import sys

def main(i):
    return i*3

if __name__ == '__main__':
    main(*sys.argv[1:])

I get only 0. I think get response from print() and process.communicate() not the best way.

Upvotes: 0

Views: 2300

Answers (1)

JanLikar
JanLikar

Reputation: 1306

Processes can't return values in the same sense a function can.

They can only set an exit code (which is the 0 you get).

You can, however, use stdin and stdout to communicate between the main script and child.py.

To "return" something from a child, just print the value you want to return.

# child.py
print("Hello from child")

The parent would do something like this:

process = Popen(command, stdout=PIPE, stdin=PIPE)
stdout, stderr = Popen.communicate()
assert stdout == "Hello from child"

Upvotes: 1

Related Questions