我有一个外部过程,它需要一些随机的时间来运行,最后它在标准输出中打印了一些输出。
我需要编写一个运行此类外部过程n次的Python过程;x秒后,对于已经终止的每个过程必须收集输出,对于尚未终止的过程,必须杀死它。
您将如何做?
您可以使用内置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.)
您可以使用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()