Python,在上一次迭代结束后立即运行shell脚本。

时间:2017-03-28 14:40:56

标签: python bash python-2.7 shell python-multithreading

我正在尝试编写一个简单的程序来调用shell脚本。我需要连续执行shell脚本,但不是在给定的时间间隔内,因为我无法准确知道shell脚本创建的进程需要多长时间才能完成。目前我已经使用线程来每N秒运行一次脚本。我需要的是,一旦“test.sh”结束,再次运行“test.sh”。

这是我目前的代码。

import subprocess
import threading

looptime = 7.0

def recognize():
    threading.Timer(looptime,recognize).start()
    filepath = "/home/user/Downloads/image.jpg"

    output = subprocess.check_output(['dir/test.sh',str(filepath)])
    print ("python print\n%s" % output)

recognize()

3 个答案:

答案 0 :(得分:2)

您不需要threading.Timersubprocess.check_output将阻止主进程,直到子进程完成。

import subprocess

def recognize():
    filepath = "/home/user/Downloads/image.jpg"

    output = subprocess.check_output(['dir/test.sh',str(filepath)])
    print ("python print\n%s" % output)

while True:
    recognize()

答案 1 :(得分:0)

bash脚本示例,它将在无限循环中执行test.sh脚本,例如:

while循环

#!/bin/bash
while :
do
    echo "running script"
    ./test.sh
done

for loop

#!/bin/bash
for (( ; ; ))
do
    echo "running script"
    ./test.sh
done

答案 2 :(得分:0)

您可以使用subprocess.check_call(cmd_line)

它会阻塞,直到子进程完成。

check_call()返回后,您可以立即启动新实例。