溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么理解Python與Shell腳本的交互

發(fā)布時間:2020-08-25 10:12:22 來源:億速云 閱讀:179 作者:Leah 欄目:編程語言

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

考慮這樣一個問題,有hello.py腳本,輸出”hello, world!”;有TestInput.py腳本,等待用戶輸入,然后打印用戶輸入的數(shù)據(jù)。那么,怎么樣把hello.py輸出內(nèi)容發(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類的構(gòu)造函數(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()

看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI