The hello.py code is as follows:
#!/usr/bin/python"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 simply executes the shell command, returning a return code (0 means the execution succeeds or fails)
retcode = os.system("python hello.py")print("retcode is: %s" % retcode);
Output:
is0
2.os.popen (CMD)
Executes the command and returns the input stream or output stream of the executing command program. This command only operates one-way streams, interacts with shell commands one-way, and cannot interact in two directions.
Returns the program output stream, connected to the output stream with a fouput variable
os.popen("python hello.py")result = fouput.readlines()print("result is: %s" % result);
Output:
resultis: [‘hello, world!\n‘]
Returns the input stream, connected to the output stream with a finput variable
finput = os.popen("python TestInput.py""w")finput.write("how are you\n")
Output:
stringis: how are you
3. Using the Subprocess Module Subprocess.call ()
Like Os.system (), note that the "shell=true" here means executing the command with the shell instead of the default OS.EXECVP ().
f = call("python hello.py", shell=True)print f
Output:
helloworld!0
Subprocess. Popen ()
The use of Popen can be a bidirectional flow of communication, you can send a program's output stream to another program's input stream.
Popen () is a constructor for the Popen class, and communicate () returns a tuple (Stdoutdata, stderrdata).
p1 = Popen("python hello.py"stdinstdout = PIPE, shell=True)p2 = Popen("python TestInput.py"stdin = p1.stdoutstdout = PIPE, shell=True)print p2.communicate()[0]#other way#print p2.stdout.readlines()
Output:
stringis: hello, world!
The integration code is as follows:
#!/usr/bin/pythonImportOs fromSubprocessImportPopen, 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 is you\n") F = Call ("Python hello.py", shell=True)PrintFP1 = Popen ("Python hello.py", stdin =None, stdout = PIPE, shell=True) P2 = Popen ("Python testinput.py", stdin = p1.stdout, stdout = PIPE, shell=True)PrintP2.communicate () [0]#other#print p2.stdout.readlines ()
How Python interacts with the shell