subprocess 创建子进程执行命令语句

import subprocess

ret = subprocess.call(['ls', '-l'])
print(ret) #执行成功返回0

try:
ret = subprocess.check_call(['mv', './ab ./cd'])
print(ret)
except subprocess.CalledProcessError as e:
print(e)
执行不成功报CalledProcessError 错, 可以用try except语句捕获

ret = subprocess.check_output(['ls', '-l'], shell=True)
print(ret.decode())
执行结果保存在ret中
shell默认为False,在Linux下,shell=False时, Popen调用os.execvp()执行args指定的程序;
shell=True时,如果args是字符串,Popen直接调用系统的Shell来执行args指定的程序,
如果args是一个序列,则args的第一项是定义程序命令字符串,其它项是调用系统Shell时的附加参数
以上三个方法都会等待主进程的完成

ret = subprocess.Popen(['ping www.baidu.com'], shell=True)
print('主进程结束了')

ret = subprocess.Popen(['ping www.jd.com'], shell=True)
ret.wait()
print('主进程结束了')
Popen方法不会等待子进程结束, 可以使用wait方法阻塞

ret = subprocess.Popen(['ping www.jd.com'], shell=True)
print(ret.pid) # 查看子进程pid
ret.kill()
ret.wait()

可以在Popen建立子进程的时候改变标准输入,输出,标准错误, 并通过subprocess.PIPE将多个子进程的输入输出绑在一起
ret = subprocess.Popen(['ls', '-l'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(ret.stdout.read().decode())
print(ret.stderr.read().decode())

猜你喜欢

转载自www.cnblogs.com/zhangjian0092/p/12300040.html