我正在开发一个使用子进程模块启动外部脚本的函数,该脚本运行从服务器发送/接收数据文件,并为~10,000个不同的文件执行此操作。该服务偶尔会被挂断,如果重新启动,可以继续使用。外部脚本将文件(.xml)保存到文件夹中,因此当输入文件的数量等于输出文件夹中的* .xml文件的数量时,该功能就完成了。这是我到目前为止,第二个while循环似乎工作 - 这是监视文件夹中没有文件更新30分钟,它应该终止进程。但是,在第一个while循环中,在进程终止后,它不会重新启动。任何帮助都会很棒!
from __future__ import division
import subprocess, datetime, time, os, glob
def runIPRscan(path, input, outputdir, email, num_complete):
num_files = len(glob.glob1(outputdir,"*.xml"))
while (num_files < num_complete):
#launch process
p = subprocess.Popen(['java', '-jar', path, '$@', '-i', input, '-m', email, '-o', outputdir], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
time.sleep(180) #give the script a few minutes to get running
while p.poll is None:
#wait 30s and check again
time.sleep(30)
num_files = len(glob.glob1(outputdir,"*.xml"))
if num_files == num_complete:
break
#monitor the output folder for recent changes in last 30 minutes
now = datetime.datetime.now()
ago = now - datetime.timedelta(minutes=30) #if nothing happens in 30 minutes, relaunch service
file_list = []
for path in glob.glob(outputdir + "/*.xml"):
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(path)
if datetime.datetime.fromtimestamp(mtime) > ago:
file_list.append(path)
if not (file_list):
print("No activity in last 30 minutes, restarting service")
try:
p.terminate()
except OSError:
pass
time.sleep(10) #give it a few seconds to make sure process is closed before exiting
break
num_files = len(glob.glob1(outputdir,"*.xml"))
答案 0 :(得分:0)
我终于明白了。所以外部脚本实际上是一个问题,它给stderr一个错误信息,但我无法看到它,因为它在子进程PIPE中。所以上面的while循环是正确的(我认为),但我最终用python版本替换了外部脚本,现在似乎工作正常。感谢。