2017-12-25 26 views
0

私は外部プロセスを実行しています。実行にはランダムな時間がかかり、最後に出力が標準出力に出力されます。同じプロセスをN回実行し、X秒以内に完了していない場合は終了します。

このような外部プロセスをN回実行するPythonプロセスを作成する必要があります。 X秒後に、既に終了している各プロセスについて、出力を収集しなければならず、終了していないプロセスごとにそれを強制終了する必要があります。

どうすればよいですか?

答えて

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モジュールを使用することができます。 A(迅速で汚れた)例:

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()   
関連する問題