使用python中的子进程模块记录ROS命令的终端输出

时间:2019-12-28 19:12:15

标签: python subprocess ros

我正在尝试使用python脚本和子进程模块捕获ROS命令产生的输出。我的代码运行一个循环,并尝试在每次迭代中从STDOUT数据管道读取该行,并进行打印。如果捕获到KeyboardInterrupt异常(Ctrl-C),它将杀死该进程。但是,在roscore,roslaunch或rosrun的情况下,此代码表现得很有趣。代码如下:

#!/usr/bin/env python

import subprocess
import shlex

if __name__ == "__main__":
    args = shlex.split('roslaunch tutorial_pkg main.launch')
    print (args)
    out = subprocess.Popen(args,stdout = subprocess.PIPE)

    while out.poll() is None:
        try:
            print (out.poll())
            output = str((out.stdout.readline()).decode('utf-8'))
            if len(output) == 0 and (out.poll() is not None):
                break
            else:
                print (output)
        except (KeyboardInterrupt, SystemExit):
            out.terminate()

运行此代码时,启动节点或roscore附带的所有初始调试信息都不会打印。任何输出到STDOUT的特定节点(如上述启动文件启动的节点)都将被正常打印。但是,如果程序结束/我按Ctrl-C,则将立即打印调试信息的所有初始行(即使我的except块中没有打印命令)。有人可以解释为什么代码以这种方式表现和/或解决此问题的方法吗?

0 个答案:

没有答案
相关问题