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

时间:2017-10-22 15:05:45

标签: python list subprocess

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我想在23

等列表中打印length_pid_detectmotion_running[0]

1 个答案:

答案 0 :(得分:0)

当你想要执行一些并行任务时,

Popen很有用,比如在程序运行时逐行控制/修改打印,期望输出

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

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

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

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