使用python记录文件输出和进程超时

2024-05-01 22:06:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在查看一个大的文件列表并对所有文件运行一个命令。我想记录输出,如果命令花费5分钟以上的时间来处理一个文件,我想停止命令并转到下一个文件。在

我有两个问题:

  1. 我想将文件名记录到输出文件中,并记录输出消息。我使用Popen来记录消息,并使用communicate来记录消息,但是我用write()编写的所有文件名在整个任务完成之前都不会被写入。

  2. 我不确定如何轮询进程,并在5分钟后退出它并转到下一个文件。

以下是简化代码:

import os, fnmatch
import subprocess
import sys
f=open('filenames','w')

'Locate all files matching supplied filename pattern in and below supplied root directory.'''

def locate(pattern, root=os.curdir):        
    for path, dirs, files in os.walk(os.path.abspath(root)):
        for filename in fnmatch.filter(files, pattern):
            yield os.path.join(path, filename)


for filename in locate("*.dll"):
    f.write(filename)   
    #cmd defintion is changed for simplicity 
    cmd='cat %s' %filename
    p=subprocess.Popen(cmd,stdout=f)   
    p.communicate()[0]

Tags: 文件pathinimport命令cmd消息for
2条回答

我用的大概是:

from datetime import datetime
from time import time

import subprocess
import sys
import threading
import os

class Execution(threading.Thread):
  comm = None
  proc = None
  returncode = None
  stdoutdata = None
  stderrdate = None

  def __init__(self, comm):
    threading.Thread.__init__(self)
    self.comm = comm

  def run(self):
    self.proc = subprocess.Popen(self.comm, bufsize=-1, stdin=None,  
                               stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    self.proc.wait()
    (self.stdoutdata, self.stderrdata) = self.proc.communicate()
    self.returncode = self.proc.poll()

for curcommand in somecommandlist:
  ex = Execution(curcommand)
  starttime = time()
  ex.start()
  ex.join(some_timeout_in_seconds)

  wastimeout = False
  if (ex.isAlive()):
    wastimeout = True
    print("TIMEOUT OCCURRED @ %s" % (datetime.today(),))
    ex.proc.kill()

  ex.join()
  endtime = time()
  duration = endtime - starttime
  print("DURATION %s" % (duration,))

  exitcode = ex.returncode
  print("EXIT CODE: %s" % (exitcode,))
  print somepostprocessing(ex.stdoutdata,ex.stderrdata)
  sys.stdout.flush()

基本上:在一个单独的线程中启动进程。这是必需的,因为threading模块给您超时等待,而subprocess模块没有。等待超时;检查线程是否仍处于活动状态。如果线程是活动的,我们通过终止进程来终止它(这里,subprocess提供了一个kill()构造,threading没有),并等待线程自行结束。在

请记住,communicate()阻塞并存储来自子级stderr和stdout的完整输出,因此如果输出非常大,这可能不起作用。在

  1. f.write(filename)之后使用f.flush()。在
  2. Using module 'subprocess' with timeout

相关问题 更多 >