Day 4-9 subprocess模块

时间:2023-11-29 08:25:14

我们经常需要通过Python去执行一条系统命令或脚本,系统的shell命令是独立于你的python进程之外的,每执行一条命令,就是发起一个新进程,通过python调用系统命令或脚本的模块在python2有os.system,除了os.system可以调用系统命令,,commands,popen2等也可以,比较乱,于是官方推出了subprocess,目地是提供统一的模块来实现对系统命令或脚本的调用.

 import subprocess

 a = subprocess.run(["ipconfig", "-3all"],stdout = subprocess.PIPE,stderr = subprocess.PIPE,check=True)   # 执行一条系统命令
## stdou用来输出命令结果,stderr是错误提示.check如果出错,会报一个错误.
#print(a.stderr)
#b = subprocess.run("df -h |grep disk1",stdout = subprocess.PIPE,stderr = subprocess.PIPE,shell=True) # 如果有管道符要用这种方法 ##标准写法 # subprocess.run(['df','-h'],stderr=subprocess.PIPE,stdout=subprocess.PIPE,check=True)
# #涉及到管道|的命令需要这样写
#
# subprocess.run('df -h|grep disk1',shell=True) #shell=True的意思是这条命令直接交给系统去执行,不需要python负责解析 subprocess.call(["ipconfig", "-all"]) #执行命令,返回命令执行状态 , 0 or 非0
retcode = subprocess.call(["ls", "-l"]) #执行命令,如果命令结果为0,就正常返回,否则抛异常
subprocess.check_call(["ls", "-l"])
0 #接收字符串格式命令,返回元组形式,第1个元素是执行状态,第2个是命令结果
subprocess.getstatusoutput('ls /bin/ls')
(0, '/bin/ls') #接收字符串格式命令,并返回结果
subprocess.getoutput('ls /bin/ls')
'/bin/ls' #执行命令,并返回结果,注意是返回结果,不是打印,下例结果返回给res
res=subprocess.check_output(['ls','-l'])
res
# b'total 0\ndrwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM\n'
a = subprocess.run(["sleep 10"],stdout = subprocess.PIPE,shell=True)
a = subprocess.Popen(["sleep 10"],stdout = subprocess.PIPE,shell=True)
print(a.poll()) # a.poll() 返回执行状态,0是正常.非零不正常
a.wait() # 等待命令就结束
terminate()终止所启动的进程Terminate the process with SIGTERM kill() 杀死所启动的进程 Kill the process with SIGKILL communicate()与启动的进程交互,发送数据到stdin,并从stdout接收输出,然后等待任务结束