Python子進(jìn)程subpocess原理及用法解析
python的子進(jìn)程嘛,就是利用python打開一個(gè)子進(jìn)程(當(dāng)然像是一句廢話),但是可能和我們理解的不太一樣。
一:如何理解?
我們可能的理解:多開一個(gè)進(jìn)程運(yùn)行某個(gè)python函數(shù)(如果只想實(shí)現(xiàn)這個(gè)功能,請使用multiprocessing包)
正確的理解:python通過shell/cmd 打開一個(gè)新的程序進(jìn)程,而不限于python函數(shù),比如我們可以開一個(gè)“l(fā)s”指令的進(jìn)程列出當(dāng)前文件夾下的文件,這個(gè)“l(fā)s”指令明顯是一個(gè)shell通用函數(shù),而不是python
函數(shù):
# 打開子進(jìn)程運(yùn)行“l(fā)s”。輸出當(dāng)前文件夾下文件<br data-filtered='filtered'>import subprocessp = subprocess.run(['ls'])
二. 如何使用?
當(dāng)我們想單純地利用subprocess打開一個(gè)進(jìn)程運(yùn)行python函數(shù)的時(shí)候,我們甚至要迂回地去做:
比方說這樣:
(1)新建一個(gè)需要運(yùn)行的函數(shù)腳本 test_print.py
import sysdef print_it(a, b , c): print(a) print(b) print(c)if __name__ == '__main__': print_it(sys.argv[1], sys.argv[2], sys.argv[3])
(2)再建一個(gè)腳本,通過傳遞參數(shù)的方式運(yùn)行 test_print.py
import subprocessp = subprocess.run(['python', 'test_print.py', 'a1', 'b2', 'c3'])pp = subprocess.run(['python', 'test_print.py', 'd4', 'e5', 'f6'])
(3) 輸出結(jié)果:
a1
b2
c3
d4
e5
f6
三:一些簡單用法
1. 比方說重定向輸出:
(1)依舊是新建一個(gè)需要運(yùn)行的函數(shù)腳本 test_print.py
import sysdef print_it(a, b , c): print(a) print(b) print(c)if __name__ == '__main__': print_it(sys.argv[1], sys.argv[2], sys.argv[3])
(2)再建一個(gè)腳本,通過傳遞參數(shù)的方式運(yùn)行 test_print.py
import subprocessp = subprocess.Popen(['python', 'test_print.py', 'a1', 'b2', 'c3'], stdout=subprocess.PIPE, shell=True) #shell=True 為必須,否則stdout無法讀出pp = subprocess.Popen(['python', 'test_print.py', 'd4', 'e5', 'f6'], stdout=subprocess.PIPE, shell=True) print(p.stdout.read()) print(pp.stdout.read())
然而此時(shí),輸出的結(jié)果是二進(jìn)制文件
b’a1rnb2rnc3rn’b’d4rne5rnf6rn’
我們需要對此進(jìn)行處理(當(dāng)然你不處理也可以,就是看著別扭)
import subprocessp = subprocess.Popen(['python', 'test_print.py', 'a1', 'b2', 'c3'], stdout=subprocess.PIPE, shell=True) #shell=True 為必須,否則stdout無法讀出pp = subprocess.Popen(['python', 'test_print.py', 'd4', 'e5', 'f6'], stdout=subprocess.PIPE, shell=True) # 用str轉(zhuǎn)化一下就好。print(str(p.stdout.read(), encoding = 'utf8'))print(str(pp.stdout.read(), encoding = 'utf8'))
(3)定向到外部文件
import subprocess# 注意,此步驟為必須f_handler=open(’out.log’, ’w’)p = subprocess.run(['python', 'test_print.py', 'a1', 'b2', 'c3'], stdout=f_handler)pp = subprocess.run(['python', 'test_print.py', 'd4', 'e5', 'f6'], stdout=f_handler)# 一個(gè)錯(cuò)誤用法p_error = subprocess.run(['python', 'test_print.py', 'd4', 'e5', 'f6'], stdout=’out.log’) # 這樣是不行的
我們會(huì)發(fā)現(xiàn),屏幕上什么都不會(huì)顯示,輸出結(jié)果已經(jīng)導(dǎo)入到out.log里面了
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. html中的form不提交(排除)某些input 原創(chuàng)2. ASP動(dòng)態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗(yàn)分享3. ASP常用日期格式化函數(shù) FormatDate()4. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫特效5. asp.net core項(xiàng)目授權(quán)流程詳解6. XMLHTTP資料7. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式8. CSS3中Transition屬性詳解以及示例分享9. jsp文件下載功能實(shí)現(xiàn)代碼10. 開發(fā)效率翻倍的Web API使用技巧
