Python中subprocess模塊用法實例詳解
本文實例講述了Python中subprocess模塊用法。分享給大家供大家參考。具體如下:
執(zhí)行命令:
>>> subprocess.call(["ls", "-l"])
0
>>> subprocess.call("exit 1", shell=True)
1
測試調(diào)用系統(tǒng)中cmd命令,顯示命令執(zhí)行的結(jié)果:
x=subprocess.check_output(["echo", "Hello World!"],shell=True) print(x) "Hello World!"
測試在python中顯示文件內(nèi)容:
y=subprocess.check_output(["type", "app2.cpp"],shell=True) print(y) #include <iostream> using namespace std; ......
查看ipconfig -all命令的輸出,并將將輸出保存到文件tmp.log中:
handle = open(r'd:\tmp.log','wt') subprocess.Popen(['ipconfig','-all'], stdout=handle)
查看網(wǎng)絡設置ipconfig -all,保存到變量中:
output = subprocess.Popen(['ipconfig','-all'], stdout=subprocess.PIPE,shell=True)
oc=output.communicate()#取出output中的字符串
#communicate() returns a tuple (stdoutdata, stderrdata).
print(oc[0]) #打印網(wǎng)絡信息
Windows IP Configuration
Host Name . . . . .
我們可以在Popen()建立子進程的時候改變標準輸入、標準輸出和標準錯誤,并可以利用subprocess.PIPE將多個子進程的輸入和輸出連接在一起,構(gòu)成管道(pipe):
child1 = subprocess.Popen(["dir","/w"], stdout=subprocess.PIPE,shell=True)
child2 = subprocess.Popen(["wc"], stdin=child1.stdout,stdout=subprocess.PIPE,shell=True)
out = child2.communicate()
print(out)
(' 9 24 298\n', None)
如果想頻繁地和子線程通信,那么不能使用communicate();因為communicate通信一次之后即關(guān)閉了管道.這時可以試試下面的方法:
p= subprocess.Popen(["wc"], stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
p.stdin.write('your command')
p.stdin.flush()
#......do something
try:
#......do something
p.stdout.readline()
#......do something
except:
print('IOError')
#......do something more
p.stdin.write('your other command')
p.stdin.flush()
#......do something more
希望本文所述對大家的Python程序設計有所幫助。
相關(guān)文章
Python實現(xiàn)將多張圖片合成視頻并加入背景音樂
這篇文章主要為大家介紹了如何利用Python實現(xiàn)將多張圖片合成mp4視頻,并加入背景音樂。文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下2022-04-04
Python協(xié)程asyncio模塊的演變及高級用法
網(wǎng)上很多關(guān)于Python協(xié)程asyncio模塊的教程都是基于老版Python的, 本文將以對比方式展示新老Python版本下協(xié)程的寫法有什么不同并總結(jié)了asyncio的一些高級用法, 包括如何獲取協(xié)程任務執(zhí)行結(jié)果,gather和wait方法的區(qū)別以及如何給任務添加回調(diào)函數(shù)。2021-05-05
python tensorflow學習之識別單張圖片的實現(xiàn)的示例
本篇文章主要介紹了python tensorflow學習之識別單張圖片的實現(xiàn)的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02
python 實現(xiàn)判斷ip連通性的方法總結(jié)
下面小編就為大家分享一篇python 實現(xiàn)判斷ip連通性的方法總結(jié),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04
Python調(diào)用REST API接口的幾種方式匯總
這篇文章主要介紹了Python調(diào)用REST API接口的幾種方式匯總,幫助大家更好的利用python進行自動化運維,感興趣的朋友可以了解下2020-10-10

