Python子進程subpocess原理及用法解析
python的子進程嘛,就是利用python打開一個子進程(當(dāng)然像是一句廢話),但是可能和我們理解的不太一樣。
一:如何理解?
我們可能的理解:多開一個進程運行某個python函數(shù)(如果只想實現(xiàn)這個功能,請使用multiprocessing包)
正確的理解:python通過shell/cmd 打開一個新的程序進程,而不限于python函數(shù),比如我們可以開一個“l(fā)s”指令的進程列出當(dāng)前文件夾下的文件,這個“l(fā)s”指令明顯是一個shell通用函數(shù),而不是python
函數(shù):
# 打開子進程運行“l(fā)s”。輸出當(dāng)前文件夾下文件<br data-filtered="filtered">import subprocess
p = subprocess.run(["ls"])
二. 如何使用?
當(dāng)我們想單純地利用subprocess打開一個進程運行python函數(shù)的時候,我們甚至要迂回地去做:
比方說這樣:
(1)新建一個需要運行的函數(shù)腳本 test_print.py
import sys def 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)再建一個腳本,通過傳遞參數(shù)的方式運行 test_print.py
import subprocess p = 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)依舊是新建一個需要運行的函數(shù)腳本 test_print.py
import sys def 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)再建一個腳本,通過傳遞參數(shù)的方式運行 test_print.py
import subprocess p = 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())
然而此時,輸出的結(jié)果是二進制文件
b'a1\r\nb2\r\nc3\r\n'
b'd4\r\ne5\r\nf6\r\n'
我們需要對此進行處理(當(dāng)然你不處理也可以,就是看著別扭)
import subprocess p = 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)# 一個錯誤用法
p_error = subprocess.run(["python", "test_print.py", "d4", "e5", "f6"], stdout='out.log') # 這樣是不行的
我們會發(fā)現(xiàn),屏幕上什么都不會顯示,輸出結(jié)果已經(jīng)導(dǎo)入到out.log里面了
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
運籌學(xué)-Python實現(xiàn)圖論與最短距離
需要求解任意兩個節(jié)點之間的最短距離,使用?Floyd?算法,只要求解單源最短路徑問題,有負權(quán)邊時使用?Bellman-Ford?算法,沒有負權(quán)邊時使用?Dijkstra?算法,本節(jié)我們只討論Dijkstra?算法,需要的朋友可以參考一下2022-01-01
python爬蟲構(gòu)建代理ip池抓取數(shù)據(jù)庫的示例代碼
這篇文章主要介紹了python爬蟲構(gòu)建代理ip池抓取數(shù)據(jù)庫的示例代碼,幫助大家更好的使用爬蟲,感興趣的朋友可以了解下2020-09-09
python 根據(jù)列表批量下載網(wǎng)易云音樂的免費音樂
這篇文章主要介紹了python 根據(jù)列表下載網(wǎng)易云音樂的免費音樂,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下2020-12-12
在Python中使用AOP實現(xiàn)Redis緩存示例
本篇文章主要介紹了在Python中使用AOP實現(xiàn)Redis緩存示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-07-07

