Illustrate how the Python program interacts with system shell

  • 2020-05-07 20:00:26
  • OfStack

Summary of

Consider the following: hello.py script, output "hello, world!" ; There is an TestInput.py script that waits for user input and then prints the data that the user enters. So, how to send the hello.py output to TestInput.py, and finally TestInput.py prints the received "hello, world!" . Let me step through the interaction of shell.

hello.py code is as follows:


#!/usr/bin/python
print "hello, world!"


TestInput.py code is as follows:


#!/usr/bin/python
str = raw_input()
print("input string is: %s" % str)

1.os.system(cmd)

This method simply executes the shell command and returns a return code (0 for success, or failure)


retcode = os.system("python hello.py")
print("retcode is: %s" % retcode);

Output:


hello, world!
retcode is: 0

2.os.popen(cmd)

Execute a command and return the input or output stream of the executing command program. This command can only operate on a one-way flow, one-way interaction with the shell command, not two-way interaction.
Returns the program output stream, connected 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, connected 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. Use subprocess module


subprocess.call()

Similar to os.system (), notice that "shell=True" here means that the command is executed with shell instead of the default os.execvp ().


f = call("python hello.py", shell=True)
print f

Output:


#!/usr/bin/python
str = raw_input()
print("input string is: %s" % str)

0

subprocess.Popen()

With Popen, two-way flow communication can be realized, and the output stream of one program can be sent to the input stream of another program.
Popen() is the constructor of the Popen class,communicate() returns a tuple (stdoutdata, stderrdata).


#!/usr/bin/python
str = raw_input()
print("input string is: %s" % str)

1

Output:


#!/usr/bin/python
str = raw_input()
print("input string is: %s" % str)

2

The integrated 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 TestInput.py", stdin = p1.stdout, stdout = PIPE, shell=True)
print p2.communicate()[0]
#other way
#print p2.stdout.readlines()


Related articles: