怎么理解Python與Shell腳本的交互?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。

專業(yè)領域包括成都網(wǎng)站設計、成都做網(wǎng)站、商城網(wǎng)站定制開發(fā)、微信營銷、系統(tǒng)平臺開發(fā), 與其他網(wǎng)站設計及系統(tǒng)開發(fā)公司不同,創(chuàng)新互聯(lián)建站的整合解決方案結合了幫做網(wǎng)絡品牌建設經(jīng)驗和互聯(lián)網(wǎng)整合營銷的理念,并將策略和執(zhí)行緊密結合,為客戶提供全網(wǎng)互聯(lián)網(wǎng)整合方案。
考慮這樣一個問題,有hello.py腳本,輸出”hello, world!”;有TestInput.py腳本,等待用戶輸入,然后打印用戶輸入的數(shù)據(jù)。那么,怎么樣把hello.py輸出內容發(fā)送給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)
這種方式只是執(zhí)行shell命令,返回一個返回碼(0表示執(zhí)行成功,否則表示失敗)
retcode = os.system("python hello.py")
print("retcode is: %s" % retcode);輸出:
hello, world! retcode is: 0
2.os.popen(cmd)
執(zhí)行命令并返回該執(zhí)行命令程序的輸入流或輸出流.該命令只能操作單向流,與shell命令單向交互,不能雙向交互.
返回程序輸出流,用fouput變量連接到輸出流
fouput = os.popen("python hello.py")
result = fouput.readlines()
print("result is: %s" % result);輸出:
result is: ['hello, world!\n']
返回輸入流,用finput變量連接到輸出流
finput = os.popen("python TestInput.py", "w")
finput.write("how are you\n")輸出:
input string is: how are you
3.利用subprocess模塊
subprocess.call()
類似os.system(),注意這里的”shell=True”表示用shell執(zhí)行命令,而不是用默認的os.execvp()執(zhí)行.
f = call("python hello.py", shell=True)
print f輸出:
hello, world! 0 subprocess.Popen()
利用Popen可以是實現(xiàn)雙向流的通信,可以將一個程序的輸出流發(fā)送到另外一個程序的輸入流.
Popen()是Popen類的構造函數(shù),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]
#other way
#print p2.stdout.readlines()輸出:
input string is: hello, world!
整合代碼如下:
#!/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()看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對創(chuàng)新互聯(lián)的支持。
網(wǎng)站名稱:怎么理解Python與Shell腳本的交互
文章位置:http://chinadenli.net/article30/pgjcpo.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供Google、網(wǎng)站排名、響應式網(wǎng)站、網(wǎng)頁設計公司、ChatGPT、移動網(wǎng)站建設
聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)