python subprocess模块之打印子进程的输出

在程序中用到了subprocess的popen来运行命令,要想获得子进程的输出,可以把输出显示出来,或者是把输出放到队列或者是列表里面处理。

为了调试先实现简单的功能,我先使用了print函数先把子进程的输出打印出来,以看到输出结果,从而判断子进程的命令运行是否正确。

部分代码如下:

class flash_update(object):

    def __init__(self):

        self.proc = None

        pass

    def start_update_patch(self):

        cur_dir = os.getcwd()

        print("cur working path is:{}".format(cur_dir))

        os.chdir(PackageParser.getInstance().get_path())  # 切换到指定的目录

        print("the flash command is {}".format(flash_command))

        subproc = subprocess.Popen(flash_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.STDOUT,universal_newlines=True, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP) #popen的配置

        self.proc = subproc

        time.sleep(1)  # wait auto reboot done

        while True:  #循环打印知道没有输出为止

            line = subproc.stdout.readline() #读取stdout的输出

            print(line) #打印输出结果

            if not line:

                break

以上程序的问题是,如果这个子进程一直有输出,那么这个进程就会被占住,代码会一直运行在此处,所以如果要在打印的同时还要做其他操作,就需要额外的处理,比如新开线程或者把这个输出写到文本里面做其他处理等。

你可能感兴趣的:(python subprocess模块之打印子进程的输出)