Overview
Consider such a problem, there is hello.py script, output "Hello, world!" ; There are testinput.py scripts, waiting for user input, and then printing data entered by the user. So, how to send hello.py output to testinput.py, finally testinput.py print received "Hello, world!." Let me explain how the shell interacts with each other step-by-step.
The hello.py code is as follows:
#!/usr/bin/python
print "Hello, world!"
The testinput.py code is as follows:
#!/usr/bin/python
str = raw_input ()
Print ("Input string is:%s"% str)
1.os.system (CMD)
This is done only by executing the shell command, which returns a return code (0 indicates that the execution succeeded or failed)
Retcode = Os.system ("python hello.py")
print ("Retcode is:%s"% retcode);
Output:
Hello, world!
. Retcode is:0
2.os.popen (CMD)
Executes the command and returns the input stream or output stream of the execution command program. This command can only operate one-way flows, with the shell command one-way interaction, not two-way interaction.
Returns the program output stream, connecting to the output stream with the Fouput variable
Fouput = Os.popen ("python hello.py") Result
= Fouput.readlines ()
print (' result is:%s '% result);
Output:
Result is: [' Hello, world!\n ']
Returns the input stream, connecting to the output stream with the Finput variable
Finput = Os.popen ("Python testinput.py", "W")
finput.write ("How are you\n")
Output:
Input string is:how are you
3. Using the Subprocess module
Like Os.system (), note that the "shell=true" here means executing the command with the shell, rather than using the default OS.EXECVP ().
F = Call ("Python hello.py", shell=true)
print F
Output:
Subprocess. Popen ()
Using Popen can be a two-way flow of communication, you can send a program output stream to another program's input stream.
Popen () is the constructor of the Popen class, and communicate () returns tuples (Stdoutdata, stderrdata).
P1 = Popen ("Python hello.py", stdin = None, stdout = PIPE, shell=true)
P2 = Popen ("Python testinput.py", stdin = P1.st Dout, stdout = PIPE, shell=true)
print p2.communicate () [0]
#other way
#print p2.stdout.readlines ()
Output:
Input string Is:hello, world!
The consolidated code is as follows:
#!/usr/bin/python
import os
from subprocess import Popen, PIPE, call
Retcode = Os.system ("Python hello.py")
print ("Retcode is:%s"% retcode);
Fouput = Os.popen ("python hello.py") Result
= Fouput.readlines ()
print (' result is:%s '% result);
Finput = Os.popen ("Python testinput.py", "W")
finput.write ("How are you\n")
f = Call ("Python hello.py", shell= True)
print f
p1 = Popen ("Python hello.py", stdin = None, stdout = PIPE, shell=true)
P2 = Popen ("Python Tes tinput.py ", stdin = p1.stdout, stdout = PIPE, shell=true)
print p2.communicate () [0]
#other way
#print P2.stdout.readlines ()