将 popen 输出转换为列表,然后执行操作


def calc_execution():
    import subprocess
    get_pid_detectmotion = "pgrep -f detectmotion.py"
    pidcmd = subprocess.Popen(get_pid_detectmotion.split(), stdout=subprocess.PIPE)
    pidcmd, error = pidcmd.communicate()
    #print pidcmd
    #detectmotion_file_pid = int(out.rstrip())
    get_length_pid_running="ps -o etime= -p" + pidcmd
    length_pid_detectmotion_running = subprocess.Popen(get_length_pid_running.split())#, int(pidcmd))
    print length_pid_detectmotion_running
    print list(length_pid_detectmotion_running)

输出:

TypeError: 'Popen' object is not iterable
   23:15:59

如何将length_pid_detectmotion_running的输出转换为list,然后获取最接近左侧的值(如果有 (3)。例如:23:15:59我想在像length_pid_detectmotion_running[0]这样的列表中打印出23

当您

想要执行一些并行任务时,例如在程序运行时逐行控制/修改打印,期望输出时,Popen很有用

Popen是一个结构,不能直接迭代。要获取进程标准输出的行列表,您应该将length_pid_detectmotion_running.stdout转换为列表。

但在您的情况下,您应该只使用 check_output 并拆分:

output = subprocess.check_output(get_length_pid_running.split())
toks = output.split(":")

toks的第一个元素应该是你的23

最新更新