国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

Python子進(jìn)程subpocess原理及用法解析

瀏覽:135日期:2022-07-17 11:31:37

python的子進(jìn)程嘛,就是利用python打開(kāi)一個(gè)子進(jìn)程(當(dāng)然像是一句廢話),但是可能和我們理解的不太一樣。

一:如何理解?

我們可能的理解:多開(kāi)一個(gè)進(jìn)程運(yùn)行某個(gè)python函數(shù)(如果只想實(shí)現(xiàn)這個(gè)功能,請(qǐng)使用multiprocessing包)

正確的理解:python通過(guò)shell/cmd 打開(kāi)一個(gè)新的程序進(jìn)程,而不限于python函數(shù),比如我們可以開(kāi)一個(gè)“l(fā)s”指令的進(jìn)程列出當(dāng)前文件夾下的文件,這個(gè)“l(fā)s”指令明顯是一個(gè)shell通用函數(shù),而不是python

函數(shù):

# 打開(kāi)子進(jìn)程運(yùn)行“l(fā)s”。輸出當(dāng)前文件夾下文件<br data-filtered='filtered'>import subprocessp = subprocess.run(['ls'])

二. 如何使用?

當(dāng)我們想單純地利用subprocess打開(kāi)一個(gè)進(jìn)程運(yùn)行python函數(shù)的時(shí)候,我們甚至要迂回地去做:

比方說(shuō)這樣:

(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è)腳本,通過(guò)傳遞參數(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

三:一些簡(jiǎn)單用法

1. 比方說(shuō)重定向輸出:

(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è)腳本,通過(guò)傳遞參數(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無(wú)法讀出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’

我們需要對(duì)此進(jìn)行處理(當(dāng)然你不處理也可以,就是看著別扭)

import subprocessp = subprocess.Popen(['python', 'test_print.py', 'a1', 'b2', 'c3'], stdout=subprocess.PIPE, shell=True) #shell=True 為必須,否則stdout無(wú)法讀出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里面了

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 中方县| 泊头市| 闵行区| 鞍山市| 珲春市| 梧州市| 霍州市| 翁源县| 合阳县| 集贤县| 镇平县| 云阳县| 深水埗区| 太和县| 永兴县| 舞阳县| 孟州市| 微山县| 奉新县| 广灵县| 巩留县| 合作市| 利辛县| 泾阳县| 特克斯县| 芒康县| 介休市| 林芝县| 区。| 宝应县| 沅陵县| 遂平县| 台州市| 阜宁县| 铜陵市| 阿瓦提县| 南平市| 阜新| 西昌市| 徐州市| 江华|