Python模块-subprocess模块

简介

定义有数个创建子进程的函数,这些函数分别以不同的方式创建子进程,所以我们可以根据需要来从中选取一个使用

用法

import subprocess
参数([命令][解释器])

subprocess.Popen()

以下的几个函数都是基于Popen()的封装(wrapper)。这些封装的目的在于让我们容易使用子进程。当我们想要更个性化我们的需求的时候,就要转向Popen类,该类生成的对象用来代表子进程。

import subprocess
retcode = subprocess.Popen('dir',shell=True)
print(retcode)
<subprocess.Popen object at 0x0000021A4F0ADA90>
 驱动器 F 中的卷是 office
 卷的序列号是 25A0-6BA3

 F:\python\test 的目录

2018/05/03  10:48    <DIR>          .
2018/05/03  10:48    <DIR>          ..

subprocess.call()

父进程等待子进程完成

返回退出信息(returncode,相当于Linux exit code)

import subprocess
retcode = subprocess.call('dir',shell=True)
print(retcode)
 驱动器 F 中的卷是 office
 卷的序列号是 25A0-6BA3

 F:\python\test 的目录

2018/05/03  10:43    <DIR>          .
2018/05/03  10:43    <DIR>          ..
0

subprocess.check_call()

父进程等待子进程完成

检查退出信息,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性,可用try…except…来检查

import subprocess
retcode = subprocess.check_call('dir',shell=True)
print(retcode)
 驱动器 F 中的卷是 office
 卷的序列号是 25A0-6BA3

 F:\python\test 的目录

2018/05/03  10:43    <DIR>          .
2018/05/03  10:43    <DIR>          ..
0

subprocess.check_output()

父进程等待子进程完成,返回子进程向标准输出的输出结果

检查退出信息,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性和output属性,output属性为标准输出的输出结果,可用try…except…来检查。

retcode = subprocess.check_output('dir',shell=True)
print(retcode)
b' \xc7\xfd\xb6\xaf\xc6\xf7 F \xd6\xd0\xb5\xc4\xbe\xed\xca\xc7 office\r\n \xbe\xed\xb5\xc4\xd0\xf2\xc1\xd0\xba\xc5\xca\xc7 25A0-6BA3\r\n\r\n F:\\python\\test \xb5\xc4\xc4\xbf\xc2\xbc\r\n\r\n2018/05/03  10:41    <DIR>          .\r\n2018/05/03  10:41    <DIR>          ..\r\n2018/05/03  10:41               165 sub.py\r\n2018/05/02  14:23               694 TCP\xbf\xcd\xbb\xa7\xb6\xcb.py\r\n2018/05/03  08:38             1,086 TCP\xb7\xfe\xce\xf1\xb6\xcb.py\r\n2018/05/03  09:18               687 UDP\xbf\xcd\xbb\xa7\xb6\xcb.py\r\n2018/05/03  09:18               721 UDP\xb7\xfe\xce\xf1\xb6\xcb.py\r\n2018/05/02  09:14                 0 __init__.py\r\n               6 \xb8\xf6\xce\xc4\xbc\xfe          3,353 \xd7\xd6\xbd\xda\r\n               2 \xb8\xf6\xc4\xbf\xc2\xbc 245,565,284,352 \xbf\xc9\xd3\xc3\xd7\xd6\xbd\xda\r\n'

猜你喜欢

转载自my.oschina.net/zhaojunhui/blog/1806005
今日推荐