4

次のコードを使用して 2 つのコマンドを 10 秒間並行して実行しようとしていますが、出力からわかるように、プロセス全体に 10 秒以上かかります。この質問の理由と最適な解決策をよりよく理解するのを手伝ってください。

stime = datetime.datetime.now()
print stime
commands = ("sudo /usr/local/bin/snort -v -u snort -g snort -c /usr/local/snort/etc/snort.conf -i eth0 &", "sudo gedit test")
for p in commands:
    p = subprocess.Popen(shlex.split(p), stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
    class Alarm(Exception):
        pass
    def alarm_handler(signum, frame):
        raise Alarm
    signal.signal(signal.SIGALRM, alarm_handler)
    signal.alarm(10) #in seconds
    try:
        stdoutdata, stderrdata = p.communicate()
        signal.alarm(0) #reset the alarm
    except Alarm:
        print 'Ooops, taking too long!!!!'
etime = datetime.datetime.now() 
print etime

そして出力:

2013-01-08 03:30:00.836412
Ooops, taking too long!!!!
2013-01-08 03:30:16.548519
4

2 に答える 2

2

threading.Timer私はより適切かもしれないように感じます:

from threading import Timer
from subprocess import Popen,PIPE
import shlex
import datetime
import sys

jobs = ['sleep 100','sleep 200']

timers = []
processes = []
print datetime.datetime.now()
for job in jobs:
    p = Popen(shlex.split(job),stdout = PIPE)
    t = Timer(10,lambda p=p: p.terminate())
    t.start()
    timers.append(t)
    processes.append(p)

for t in timers:
    t.join()

stdout,stderr = processes[0].communicate()    
stdout,stderr = processes[1].communicate()
print datetime.datetime.now()
于 2013-01-11T02:07:20.773 に答える
1
import multiprocessing
import subprocess
import shlex
import time

commands = ("echo -n HI-FIRST ", "echo -n HI-SECOND ")
def parallel():
    p = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
    stdoutdata, stderrdata = p.communicate()
    print stdoutdata + "\t" + time.ctime()
for cmd in commands:
    p = multiprocessing.Process(target=parallel)
    p.start()

出力:

$ python stack.py 
HI-FIRST    Fri Jan 11 08:47:18 2013
HI-SECOND   Fri Jan 11 08:47:18 2013
于 2013-01-11T02:50:34.367 に答える