For example, the Python program interacts with the system shell.
Overview
To solve this problem, we have a hello. py script that outputs "hello, world !"; There is a TestInput. py script, waiting for user input, and then printing user input data. Then, how to send the hello. py output content to TestInput. py, and finally TestInput. py prints the received "hello, world !". Next I will explain the shell interaction method step by step.
The hello. py code is as follows:
#!/usr/bin/pythonprint "hello, world!"
The TestInput. py code is as follows:
#!/usr/bin/pythonstr = raw_input()print("input string is: %s" % str)
1. OS. system (cmd)
This method only executes the shell command and returns a return code (0 indicates that the execution is successful, otherwise it indicates that the execution fails)
retcode = os.system("python hello.py")print("retcode is: %s" % retcode);
Output:
hello, world!retcode is: 0
2. OS. popen (cmd)
Execute the command and return the input stream or output stream of the command execution program. This command can only operate on one-way streams, one-way interaction with shell commands, not two-way interaction.
Returns the program output stream and uses the fouput variable to connect to the output stream.
fouput = os.popen("python hello.py")result = fouput.readlines()print("result is: %s" % result);
Output:
result is: ['hello, world!\n']
Returns the input stream and connects to the output stream using 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 the subprocess Module
subprocess.call()
Kerberos.system({, here the zookeeper true=command is executed with shell, but not with the same OS .exe cvp.
f = call("python hello.py", shell=True)print f
Output:
hello, world!0
Subprocess. Popen ()
Popen can be used to implement bidirectional stream communication and send the output stream of a program to the input stream of another program.
Popen () is the Popen class constructor. communicate () returns the tuples (stdoutdata, stderrdata ).
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()
Output:
input string is: hello, world!
The integration code is as follows:
#!/usr/bin/pythonimport osfrom subprocess import Popen, PIPE, callretcode = 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 fp1 = 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()