How to Change Python Output to PID
Changing the destination of the stdout output to another process in Python provides you with a type of communication between the two processes. The stdout, or standard output, is a pipe that controls where the program writes its output data. Typically, the stdout points to the terminal so the program can communicate with the user by displaying text on the screen. Call the popen and communicate functions from the Python subprocess module to attach the stdout output to another process.
Instructions
-
-
1
Open the Python source file with your preferred text editor.
-
2
Open a process and connect stdout to the PID/PIPE of the process by typing the following code at the top of your script:
import subprocess
print '\nstdout set to pipe:'
ch_proc = subprocess.Popen(['echo', '"sent"'],
stdout=subprocess.PIPE,
)
stdout_val = ch_proc.communicate()[0]
print ' stdout - ', repr(stdout_val)This lets the calling process access output data from the other process.
-
-
3
Open a process and connect stdin to the PID/PIPE of the process by typing this code:
import subprocess
print 'stdin set to pipe'
ch_proc = subprocess.Popen(['cat', '-'],
stdin=subprocess.PIPE,
)
ch_proc.communicate('stdin - stdin')The code lets the calling process write data to the other process through the stdin stream.
-
4
Save the script with a .py extension and execute it at the command prompt by typing:
$ python -u myfile.py
-
1