subprocess.Popopen用法

2021-04-22  本文已影响0人  非鱼2018
#coding=utf-8
import subprocess

# 如果使用了stdout=subprocess.PIPE,则要自己打印输出,否则控制台不会打印
#
result=subprocess.Popen('dir',shell=True,stderr=subprocess.PIPE,stdout=subprocess.PIPE)

result.wait()
outs,errs=result.communicate()  #返回元组,标准输出以及err
#执行成功则打印输出的信息
if result.returncode==0:
    for i in outs.splitlines():
        print(i.decode('GBK')) #UTF-8

只想获取失败信息,忽略成功信息

result=subprocess.Popen('ddd',shell=True,stderr=subprocess.PIPE,stdout=subprocess.PIPE)

result.wait()
outs,errs=result.communicate()
#执行成功则打印输出的信息
if not result.returncode==0:
    for i in errs.splitlines():
        print(i.decode('GBK')) #UTF-8

有时调用稍微复杂的命令,该命令又会调用其他命令,虽然返回时0,但err却不为空,因此再加层判断

result=subprocess.Popen('ddd',shell=True,stderr=subprocess.PIPE,stdout=subprocess.PIPE)

result.wait()
outs,errs=result.communicate()
#执行成功则打印输出的信息 注意b''即使为不为None,因此不能用not None来判断
if not result.returncode==0 or not len(errs)==0:
    for i in errs.splitlines():
        print(i.decode('GBK')) #返回为字节,需要转成str
    for i in outs.splitlines():
        print(i.decode('GBK'))  # UTF-8

上一篇下一篇

猜你喜欢

热点阅读