1. 程式人生 > >Python與shell互動os.system、 os.popen、 subprocess

Python與shell互動os.system、 os.popen、 subprocess

這篇文章主要介紹了Python與shell的3種互動方式介紹,本文講解了

os.system、

os.popen、

subprocess

模組等3種方法,需要的朋友可以參考下。

問題概述

考慮這樣一個問題,有hello.py指令碼,輸出”hello, world!”;有TestInput.py指令碼,等待使用者輸入,然後列印使用者輸入的資料。那麼,怎麼樣把hello.py輸出內容傳送給TestInput.py,最後TestInput.py列印接收到的”hello, world!”。下面我來逐步講解一下shell的互動方式。

hello.py程式碼如下:

#!/usr/bin/python

print "hello, world!"


TestInput.py程式碼如下:

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

解決方案


1.os.system(cmd)

這種方式只是執行shell命令,返回一個返回碼(0表示執行成功,否則表示失敗)

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

輸出:

hello, world!
retcode is: 0

2.os.popen(cmd)

執行命令  並  返回該執行命令程式的   輸入流或輸出流. 該命令只能操作單向流,與shell命令單向互動,不能雙向互動.

1)返回程式輸出流,用fouput變數連線到輸出流

fouput = os.popen("python hello.py")
result = fouput.readlines()
print("result is: %s" % result);

輸出:

result is: ['hello, world!\n']

2)返回輸入流,用finput變數連線到輸出流

finput = os.popen("python TestInput.py", "w")
finput

.write("how are you\n")

輸出:

input string is: how are you (看上面TestInput.py檔案程式碼)

3.利用subprocess模組

1) subprocess.call()

類似os.system(),注意這裡的”shell=True”表示用shell執行命令,而不是用預設的os.execvp()執行

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

輸出:

hello, world!

2) subprocess.Popen()

利用Popen可以是實現雙向流的通訊,可以將一個程式的輸出流傳送到另外一個程式的輸入流.
Popen()是Popen類的建構函式,communicate()返回元組(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]
#其他方式
#print  p2.stdout.readlines()

輸出:

input string is: hello, world!

4.程式碼整合

整合程式碼如下:

#!/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()