subprocess:
sub: 子
process: 进程python
能够经过python代码给操做系统发送命令,并将执行结果返回。shell
import subprocess while True: # 1.让用户输入终端命令 cmd_str = input('请输入终端命令:').strip() # Popen(cmd命令, shell=True, # stdout=subprocess.PIPE, stderr=subprocess.PIPE) # 调用Popen就会将用户的终端命令发送给本地操做系统的终端 # 获得一个对象,对象中包含着正确或错误的结果。 obj = subprocess.Popen( cmd_str, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) success = obj.stdout.read().decode('gbk') if success: print(success, '正确的结果') error = obj.stderr.read().decode('gbk') if error: print(error, '错误的结果')
subprocess模块能够生成新的进程,链接到它们的input/output/error管道,同时获取它们的返回码。函数
(1) args:启动进程的参数,默认为字符串序列(列表或元组),也可为字符串(设为字符串时通常需将shell参数赋值为True);
(2) shell:shell为True,表示args命令经过shell执行,则可访问shell的特性;
(3) check:check为True时,表示执行命令的进程以非0状态码退出时会抛出;subprocess.CalledProcessError异常;check为False时,状态码为非0退出时不会抛出异常;
(4) stdout、stdin、stderr:分别表示程序标准标输出、输入、错误信息;
run函数返回值为CompletedProcess类,若需获取执行结果,可经过获取返回值的stdout和stderr来捕获;
check_output函数若需捕获错误信息,可经过stderr=subprocess.STDOUT来获取;操作系统
# subprocess.run使用 def subprocess_run(): print("**** subprocess.run ****") print("----------") result1 = subprocess.run(["adb", "devices"]) print("result1:", result1) print("----------") result2 = subprocess.run("adb devices", shell=True, check=True) print("result2:", result2) print("----------") result3 = subprocess.run(["adb", "devices"], stdout=subprocess.PIPE) print("result3:", result3) print(type(result3)) subprocess_run() """结果 **** subprocess.run **** ---------- List of devices attached 338b123f0504 device result1: CompletedProcess(args=['adb', 'devices'], returncode=0) ---------- List of devices attached 338b123f0504 device result2: CompletedProcess(args='adb devices', returncode=0) ---------- result3: CompletedProcess(args=['adb', 'devices'], returncode=0, stdout=b'List of devices attached \r\n338b123f0504\tdevice\r\n\r\n') <class 'subprocess.CompletedProcess'> """ # subprocess.call使用 def subprocess_call(): print("**** subprocess.call ****") print("----------") result1 = subprocess.call(["adb", "devices"]) print("result1:", result1) print("----------") result2 = subprocess.call(["adb", "devices"], stdout=subprocess.PIPE) print("result2:", result2) subprocess_call() """结果 **** subprocess.call **** ---------- List of devices attached 338b123f0504 device result1: 0 ---------- result2: 0 """ # subprocess.check_call def subprocess_check_call(): print("**** subprocess.check_call ****") print("----------") result1 = subprocess.check_call(["adb", "devices"]) print("result1:", result1) print("----------") result2 = subprocess.check_call(["adb", "devices"], stdout=subprocess.PIPE) print("result2:", result2) subprocess_check_call() """结果 **** subprocess.check_call **** ---------- List of devices attached 338b123f0504 device result1: 0 ---------- result2: 0 """ # subprocess.check_output def subprocess_check_output(): print("**** subprocess.check_output ****") print("----------") result1 = subprocess.check_output(["adb", "devices"]) print("result1:", result1) print("----------") result2 = subprocess.run(["adb", "devices"], stdout=subprocess.PIPE).stdout print("result2:", result2) subprocess_check_output() """结果 **** subprocess.check_output **** ---------- result1: b'List of devices attached \r\n338b123f0504\tdevice\r\n\r\n' ---------- result2: b'List of devices attached \r\n338b123f0504\tdevice\r\n\r\n' """
cmd:参数,字符串类型;code
# subprocess.getoutput或getstatusoutput使用 def subprocess_get_output(): print("**** subprocess.getoutput ****") result1 = subprocess.getoutput("adb devices") print("result1:", result1) print(type(result1)) print("**** subprocess.getstatusoutput ****") result2 = subprocess.getstatusoutput("adb devices") print("result2:", result2) print(type(result2)) subprocess_get_output() """结果 **** subprocess.getoutput **** result1: List of devices attached 338b123f0504 device <class 'str'> **** subprocess.getstatusoutput **** result2: (0, 'List of devices attached \n338b123f0504\tdevice\n') <class 'tuple'> """
subprocess.Popen类用于在一个新进程中执行一个子程序,上述subprocess函数均是基于subprocess.Popen类;对象
- args:须要执行的系统命令,可为字符串序列(列表或元组,shell为默认值False便可,建议为序列),也可为字符串(使用字符串时,需将shell赋值为True);
- shell:默认为False,若args为序列时,shell=False;若args为字符串时,shell=True,表示经过shell执行命令;
- stdout、stdin、stderr:分别表示子程序标准输出、标准输入、标准错误,可为subprocess.PIPE、一个有效的文件描述符、文件对象或None。
若为subprocess.PIPE:表明打开通向标准流的管道,建立一个新的管道;
若为None:表示没有任何重定向,子进程会继承父进程;
stderr也可为subprocess.STDOUT:表示将子程序的标准错误输出重定向到了标准输出- bufsize:指定缓冲策略,0表示不缓冲,1表示行缓冲,其它整数表示缓冲区大小,负数表示使用系统默认值0;
- cwd:默认值为None;若非None,则表示将会在执行这个子进程以前改变当前工做目录;
- env:用于指定子进程的环境变量。若env为None,那么子进程的环境变量将从父进程中继承;若env非None,则表示子程序的环境变量由env值来设置,它的值必须是一个映射对象。
- universal_newlines: 不一样系统的换行符不一样。若True,则该文件对象的stdin,stdout和stderr将会以文本流方式打开;不然以二进制流方式打开。
def subprocess_Popen1(): print("***经过communicate函数分别输出PopenObject对象的输出流和错误流***") args = [["adb", "devices"], ["adb", "devices11"]] for arg in args: popen_object = subprocess.Popen(arg, stdout=subprocess.PIPE, stderr=subprocess.PIPE) object_stdout, object_stderr = popen_object.communicate() output = {"popen_object": popen_object, "object_stdout": object_stdout, "object_stderr": object_stderr} print(output) """ {'popen_object': <subprocess.Popen object at 0x0000000002212400>, 'object_stdout': b'List of devices attached \r\n106D111805005938\tdevice\r\n\r\n', 'object_stderr': b''} {'popen_object': <subprocess.Popen object at 0x0000000002577C18>, 'object_stdout': b'', 'object_stderr': b'Android Debug Bridge version 1.0.31\r\n\r\n -a .....} """ print("***经过stdout和stderr方法输出PopenObject对象输出流和错误流***") p0 = subprocess.Popen(["adb", "devices"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) object_stdout = p0.stdout.read() p0.stdout.close() object_stderr = p0.stderr.read() p0.stderr.close() print(object_stdout) # 结果:b'List of devices attached \r\n338b123f0504\tdevice\r\n\r\n' print(object_stderr) # 结果:b'' print("***Popen对象stdin写入功能:使用stdout和stderr输出") args = ["python", "python1"] for arg in args: p4 = subprocess.Popen([arg], shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) p4.stdin.write("print('hello')") p4.stdin.close() out = p4.stdout.read() p4.stdout.close() err = p4.stderr.read() p4.stderr.close() print("out:%s err:%s" % (out, err)) """ ***Popen对象stdin写入功能 out:hello err: out: err:'python1' 不是内部或外部命令,也不是可运行的程序或批处理文件。 """ print("***Popen对象stdin写入功能:使用communicate输出") p4 = subprocess.Popen(["python"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) p4.stdin.write("print('hello')") output = p4.communicate() print(output) # 结果:('hello\n', '') print("***不含encoding参数***") p1 = subprocess.Popen("adb devices", shell=True, stdout=subprocess.PIPE) out1 = p1.stdout.readlines() print(out1) # 结果: [b'List of devices attached \r\n', b'106D111805005938\tdevice\r\n', b'\r\n'] print("***含encoding参数***") p2 = subprocess.Popen("adb devices", shell=True, stdout=subprocess.PIPE, encoding="utf-8") out2 = p2.stdout.readlines() print(out2) # 结果: ['List of devices attached \n', '106D111805005938\tdevice\n', '\n'] print("***Popen对象检查命令是否结束,等待进程结束") print(p2.poll()) # 结果: None print(p2.wait()) # 结果: 0 print(p2.poll()) # 结果: 0 print("***Popen对象communicate函数,它会阻塞父进程直至子进程完成") p3 = subprocess.Popen("adb devices", shell=True, stdout=subprocess.PIPE) out = p3.communicate()[0] print(out) # 结果:b'List of devices attached \r\n338b123f0504\tdevice\r\n\r\n' print(p3.poll()) # 结果:0 subprocess_Popen1() def subprocess_Popen2(): """ 1. 经过管道功能,实现adb shell ps | findstr top功能 2. 直接为args赋值为一个字符串,实现adb shell ps | findstr top功能 :return: """ print("***经过管道方式***") p1 = subprocess.Popen(["adb", "shell", "ps"], stdout=subprocess.PIPE) p2 = subprocess.Popen(["findstr", "top"], stdin=p1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p2.communicate() print(out, err) # 结果:b'shell 8508 8504 2600 1044 c004e5f8 b6f40938 S top\r\r\n' b'' print("***经过传一个字符串方式***") p3 = subprocess.Popen("adb shell ps | findstr top", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p3.communicate() print(out, err) # 结果:b'shell 8508 8504 2600 1044 c004e5f8 b6f40938 S top\r\r\n' b'' subprocess_Popen2()