subprocess模块

来源:互联网 发布:淘宝新店铺购买 编辑:程序博客网 时间:2024/04/30 03:58
import subprocess
call()
执行命令返回,返回状态码
subprocess.call('ls')#默认参数shell=False,命令参数需使用列表类型subprocess.call(['ls','-l'],shell=False)#将参数设置为shell=True,则命令可以直接使用字符串subprocess.call('ls -l',shell=True)
check_call
执行命令,若执行状态码为0则返回0,否则抛异常
subprocess.check_call('ls')
check_output
执行命令,若状态码为0则返回执行结果,否则抛异常
res = subprocess.check_output('ls')print(res)
subprocess.Popen
用于执行复杂的系统命令
import subprocess#模拟python交互解释器obj = subprocess.Popen(["python"],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True)#输入管道写命令obj.stdin.write(input("python: "))obj.stdin.close()#输出管道读结果cmd_out=obj.stdout.read()obj.stdout.close()cmd_error = obj.stderr.read()obj.stderr.close()print(cmd_out)
0 0
原创粉丝点击