首页 > 代码库 > Python subprocess
Python subprocess
#!/usr/bin/env python # -*- coding:utf-8 -*- # author: Changhua Gong import subprocess ‘‘‘ 1. 推荐使用subprocess模块代替其他模块执行shell命令; 2. call无论是否正确执行都会返回returncode attribute,即使执行命令报错了,后面的语句会继续执行, check_call & check_output执行命令报错后(returncode非0)直接抛出CalledProcessError,后续命令不再执行, 可使用try...except...捕捉; 3. call无论是否正确执行都会返回returncode attribute,即使执行命令报错了,后面的语句会继续执行; 4. check_call:Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. check_call要么返回0,要么直接抛出异常CalledProcessError,异常对象里仅有returncode; 5. check_output:Run command with arguments and return its output. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute. check_output要么返回直接返回命令运行结果(returncode为0,命令正确执行), 要么直接抛出异常CalledProcessError,异常对象里有returncode和output; ‘‘‘ rs = subprocess.call([ "ipconfig" , "/all" ]) print ( "Exit code: " , rs) # 执行后的返回结果 try : rs = subprocess.check_call([ "dir" , "c:" ]) print ( "Exit code: " , rs) # 执行后的返回结果 except Exception as e: print (e) print ( "........................................" ) try : rs = subprocess.check_output([ "dir" , "c:" ], stderr =subprocess.STDOUT) print ( "Exit code: " , rs) # 执行后的返回结果 except Exception as e: print (e) print ( "........................................" ) ‘‘‘以下命令在linux上尝试‘‘‘ import subprocess rs = subprocess.call( "ls -l hellokity" , shell = True ) print ( "Exit code: " , rs) # 执行后的返回结果 try : rs = subprocess.check_call( "ls -l hellokity" , shell = True ) except subprocess.CalledProcessError as e: print (e.returncode) try : rs = subprocess.check_output( "ls -l hellokity" , shell = True , stderr =subprocess.STDOUT) except subprocess.CalledProcessError as e: out_bytes = e.output.decode() # Output generated before error,这里需指定stderr=subprocess.STDOUT,报错后才有内容返回 code = e.returncode # Return code print (out_bytes, code) ‘‘‘Popen的交互 Popen对象创建后,主程序不会自动等待子进程完成。我们必须调用对象的wait()方法,父进程才会等待 communicate()是Popen对象的一个方法,该方法会阻塞父进程,直到子进程完成。 ‘‘‘ child1 = subprocess.Popen([ "ls" , "-l" ], stdout =subprocess.PIPE) child2 = subprocess.Popen([ "wc" , "-l" ], stdin =child1.stdout, stdout =subprocess.PIPE) stdout, stderr = child2.communicate() # 负责交互 print (stdout.decode(), stderr) text = b‘‘‘ abc 123 xya sda ‘‘‘ child = subprocess.Popen([ "wc" , "-l" ], stdin =subprocess.PIPE, stdout =subprocess.PIPE) # child.wait() #如果是调用了communicate,则不需使用wait,因为communicate自动等待子进程结束 stdout, stderr = child.communicate(text) # 负责交互 print (stdout.decode(), stderr)
本文出自 “90SirDB” 博客,请务必保留此出处http://90sirdb.blog.51cto.com/8713279/1922622
Python subprocess
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。