运行Popen后文件未读取文本文件

时间:2019-05-22 19:22:27

标签: python-3.x subprocess

我正在尝试编写一些检查特定服务的内容,并将其放入文本文件中。后遗症我试图确定它是停止还是运行,并执行其他操作。

文件已创建,看起来像这样,我尝试单独解析或使用.readlines()解析,但没有骰子。任何帮助/提示将不胜感激。

SERVICE_NAME: fax 
        TYPE               : 10  WIN32_OWN_PROCESS  
        STATE              : 1  STOPPED 
        WIN32_EXIT_CODE    : 1077  (0x435)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0

但是我下面的代码返回空或什么都没有

from subprocess import Popen
import datetime

today = datetime.datetime.now()
squery = ['sc', 'query', 'fax']
proc = Popen(['sc', 'query', 'fax'], stdout=open(str(today.date())+'_ServiceCheck.txt', 'w'))
if 'STOPPED' in open(str(today.date())+'_ServiceCheck.txt').read():
    print("Uh Oh")
    #Do Something about it

1 个答案:

答案 0 :(得分:1)

按照书面规定,父进程很有可能会打开文件,检查STOP并在子进程甚至开始运行之前就关闭。您可以使用subprocess.call强制阻塞父进程,直到子进程完成执行为止,这可能会导致等待Selenium脚本进程完成执行的想法。

考虑一下:

# some_script.py
from time import sleep

print("subprocess running!")

for i in range(5):
    print("subprocess says %s" % i)
    sleep(1)

print("subprocess stopping!")
# main.py
import subprocess

while True:
    print("parent process starting child...")
    proc = subprocess.call(["python", "some_script.py"])
    print("parent process noticed child stopped running")

运行python main.py的输出摘录:

parent process starting child...
subprocess running!
subprocess says 0
subprocess says 1
subprocess says 2
subprocess says 3
subprocess says 4
subprocess stopping!
parent process noticed child stopped running
parent process starting child...
subprocess running!
subprocess says 0
subprocess says 1
subprocess says 2
subprocess says 3
subprocess says 4
subprocess stopping!
parent process noticed child stopped running
...

这似乎好多了。父级完全阻塞,直到子级停止执行,然后立即重新启动子级。

否则,要执行您的操作,听起来您需要像下面这样定期轮询文件:

import datetime
from subprocess import Popen
from time import sleep

delay = 10

while True:
    today = datetime.datetime.now()
    fname = '%s_ServiceCheck.txt' % today.date()

    file_content = open(fname).read()

    if 'STOPPED' in file_content:       
        print('Uh oh')     
        proc = Popen(['sc', 'query', 'fax'], stdout=open(fname, 'w'))

    sleep(delay)

但是要小心-如果硒过程在11:59:59停止会怎样?轮询此文本文件非常脆弱,因此此脚本可能不够强大,无法处理所有情况。如果您可以将Selenium脚本的输出直接重定向到父进程,那将使其更加可靠。如果需要,父进程也可以代表脚本将日志写入磁盘。

无论哪种方式,很多情况都取决于您的环境以及您要实现的目标的详细信息。