执行subprocess.Popen一次后,Python程序停止

时间:2017-06-22 10:40:47

标签: python ubuntu subprocess

我正在尝试使用python中的循环多次执行命令行程序。自然地我使用了子进程模块执行此任务。但是在执行python脚本时,命令行程序运行一次然后停止。它们都不再运行它也不会返回python脚本.Below是我写的循环.'commandline'是我运行的命令及其参数

for i in range(len(final)):
    ss=str(final[i][0])
    endpos=str(final[i][1])
    op='/home/nishant/op'+str(i)
    commandline='/home/nishant/project/LOOV/build/./LOOV -v vid -output op -ss ss -endpos endpos -lang eng -print_text'
    subprocess.Popen(commandline,shell=True).communicate()

3 个答案:

答案 0 :(得分:1)

如果您希望执行命令,等待并检查代码0退出(没有遇到错误),您应该尝试使用check_output

import subprocess
your_command = 'you command(s) here'
subprocess.check_output(your_command, shell=True)

答案 1 :(得分:0)

import subprocess
A = subprocess.Popen("command", shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
print(A.communicate)

我很确定你可以从那里拿走它。

答案 2 :(得分:0)

尝试Plumbum

pip install plumbum

由于我不知道它的上下文,我开发了一个带有ifconfig命令的小例子,在一个循环中编写。

from plumbum.cmd import grep, ifconfig
from plumbum import FG, BG

lst = ['Link', 'inet', 'LOOPBACK', 'BROADCAST', '127', 'Eth']

for l in lst:
    command = ifconfig | grep[l]
    f = command & BG
    output = f.stdout
    print (output)

输出:

docker0   Link encap:Ethernet  Endereço de HW 02:42:cd:ab:75:e2  
enp3s0    Link encap:Ethernet  Endereço de HW 10:c3:7b:c4:21:e4  
          endereço inet6: fe80::8267:7328:8542:3434/64 Escopo:Link
lo        Link encap:Loopback Local  

          inet end.: 172.17.0.1  Bcast:0.0.0.0  Masc:255.255.0.0
          inet end.: 192.168.1.34  Bcast:192.168.255.255  Masc:255.255.0.0
          endereço inet6: fe80::8267:7328:8542:3434/64 Escopo:Link
          inet end.: 127.0.0.1  Masc:255.0.0.0
          endereço inet6: ::1/128 Escopo:Máquina

          UP LOOPBACK RUNNING  MTU:65536  Métrica:1

          UP BROADCAST MULTICAST  MTU:1500  Métrica:1
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Métrica:1

          inet end.: 127.0.0.1  Masc:255.0.0.0

docker0   Link encap:Ethernet  Endereço de HW 02:42:cd:ab:75:e2  
enp3s0    Link encap:Ethernet  Endereço de HW 10:c3:7b:c4:21:e4