Return value of child_process in terminal

Viewed 162

How can I return a value of an python child process, which I have started through the main.py by following code:

subprocess.check_output(['lxterminal -e  python3 rfid_input.py'], stdin=subprocess.PIPE, shell=True, close_fds=True)

parent process:

import sys, subprocess
value = subprocess.check_output(['lxterminal -e  python3 rfid_input.py'], stdin=subprocess.PIPE, shell=True, close_fds=True)
print(value)

The child process contains a simple x=input() and looks like following:

import sys
x=input()
sys.stdout.write(x)

but Ii still receive nothing else as the empty b''.

I also tried it by subprocess.Popen with .wait() and .communicate() with no success.

If you have any other ideas how I can get the value of the lxterminal input, please let me know.

1 Answers

For passing data to stdin, your setting would usually look like this

import subprocess

stdin = b"THE DATA YOU PASS"
terminal = subprocess.Popen(["lxterminal", "-e", "python3", "rfid_input.py"],
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
stdout, stderr = terminal.communicate(stdin)

When you call .communicate without arguments, it usually passes empty bytes, that might be what happened here.

Template example:

Parent:

import subprocess

stdin = b"THE DATA YOU PASS"
terminal = subprocess.Popen(["python3", "stackoverflow_child.py"],
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
stdout, stderr = terminal.communicate(stdin)
print(stdout.decode("utf-8"), stderr.decode("utf-8"))

child with name stackoverflow_child.py:

import sys
x=input()
sys.stdout.write(x * 2)  # so you can see the child was called

If you don't want to handle bytes, you can also pass encoding="utf-8" to Popen, then you can pass stdin as string and receive stdout and stderr as strings.

Related