执行相同的过程N次,如果在X秒内没有完成,则终止它

问题描述 投票:0回答:2

我有一个外部进程,需要一些随机时间来运行,最后它会在标准输出中打印一些输出。

我需要编写一个python进程,运行这样的外部进程N次;在X秒之后,对于已经终止的每个进程,它必须收集输出,并且对于尚未终止的每个进程,它必须将其终止。

你会怎么做?

python-3.x multiprocessing
2个回答
0
投票

您可以使用内置API:

http://strftime.org/ https://docs.python.org/3.5/library/time.html

start_time = time.time()
# your code
elapsed_time = time.time() - start_time
time.strftime("%H:%M:%S", time.gmtime(elapsed_time))
#'00:00:02'

要杀死这个过程,我不知道你是如何处理的:

您可以使用:

import subprocess, signal 
p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
   if 'iChat' in line:
   pid = int(line.split(None, 1)[0])
   os.kill(pid, signal.SIGKILL) # -9 (equivalent.)

0
投票

您可以使用apscheduler模块。一个(快速和肮脏)的例子:

from apscheduler.schedulers.background import BlockingScheduler

count = 0
N = 10 # Change this per your requirement

def run_external_process():
    global count, scheduler

    # Execute the job N times
    count = count + 1

    if count == 10: # Shutdown the scheduler and exit
        scheduler.shutdown(wait=False)
        sys.exit(1)

    #Run your code here

# When each job is executed check for its output 
def listen_for_output():
   if event.retval: # Check the return value of your external process
       # Collect output
   else:
       # Call script to terminate process

try:
    scheduler = BlockingScheduler() # Initiate your scheduler
except ImportError:
    raise ImportError('Failed to import module')
sys.exit(1)  

scheduler.add_job(run_external_process, 'interval', seconds=1, id='my_job_id')
# Add a listener to check the output of your external process
scheduler.add_listener(listen_for_output, EVENT_JOB_EXECUTED|EVENT_JOB_ERROR) 
scheduler.start()           
© www.soinside.com 2019 - 2024. All rights reserved.