Python的并发并行[3] -> 进程[1] -> 多进程的基本使用

本文通过具体实例介绍了Python中subprocess模块的使用方法,包括run、call、check_call等函数的应用及Popen类的交互方式,适合初学者快速掌握多进程编程技巧。

多进程的基本使用


 

1 subprocess 常用函数示例

首先定义一个子进程调用的程序,用于打印一个输出语句,并获取命令行参数

1 import sys
2 print('Called_Function.py called, Hello world.')
3 try:
4     print('Got para', sys.argv[1:])
5 except:
6     pass

再定义主函数,即父进程,分别测试 run() / call() / check_call() / getstatusoutput() / getoutput() / ckeck_output函数。

 1 import subprocess
 2 
 3 # subprocess.run()
 4 print('---------subprocess.run------------')
 5 re = subprocess.run(['python', 'Called_Function.py', 'para_1', 'para_2'])
 6 print('subprocess.run() test returns obj:', re)
 7 print('Return code is: {0}, stdout is: {1}, stderr is: {2}'.format(re.returncode, re.stdout, re.stderr))
 8 
 9 # subprocess.call()
10 print('\n---------subprocess.call------------')
11 print('subprocess.call() test returns code:', subprocess.call(['python', 'Called_Function.py', 'para_1', 'para_2']))
12 
13 # subprocess.ckeck_call()
14 print('\n---------subprocess.check_call------------')
15 try:
16     print('subprocess.check_call() test returns code:', subprocess.check_call(['python', 'Called_Function.py']))
17 except subprocess.CalledProcessError:
18     print('Failed to call.')
19 
20 # subprocess.getstatusoutput()
21 print('\n---------subprocess.getstatusoutput------------')
22 print('subprocess.getstatusoutput() test returns:', subprocess.getstatusoutput(['python', 'Called_Function.py']))
23 
24 # subprocess.getoutput()
25 print('\n---------subprocess.getstatusoutput------------')
26 print('subprocess.getoutput() test returns:', subprocess.getoutput(['python', 'Called_Function.py']))
27 
28 # subprocess.check_output()
29 print('\n---------subprocess.check_output------------')
30 print('subprocess.check_output() test returns:', subprocess.check_output(['python', 'Called_Function.py']))

 

2 利用Popen类与子进程交互

首先定义一个子进程调用的函数,函数中需求一个输入

1 x = input('Please input something.')
2 print(x, 'Hello World!')
3 # Raise an error
4 print(y)

再定义父进程的函数

 1 import subprocess
 2 
 3 prcs = subprocess.Popen(['python', 'Called_Function_Popen.py'],
 4                         stdout=subprocess.PIPE,
 5                         stdin=subprocess.PIPE,
 6                         stderr=subprocess.PIPE,
 7                         universal_newlines=True,
 8                         shell=True)
 9 
10 print('subprocess pid:', prcs.pid)
11 
12 re = prcs.communicate('These string are from stdin')
13 print('\nSTDOUT:', re[0])
14 print('\nSTDERR:', re[1])
15 if prcs.poll():
16     print('\nThe subprocess has been done')

相关阅读

1. subprocess 模块

 

转载于:https://www.cnblogs.com/stacklike/p/8167028.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值