假设我想从我的Python脚本运行两个bash命令c1和c2,这两个命令本质上是处理(但不是修改) Linux上的同一段数据(因此这不是微妙的竞态条件)。
现在我想同时启动它们(使用os.system),看看哪个进程完成得更快,一旦一个进程完成,我将收集它的输出(可以用c1 >> log1.txt将其转储到一个文件中),并终止另一个进程。
请注意,两个进程的处理时间可能有很大不同,因此可以观察到,一个进程需要10秒,而另一个进程需要60秒。
发布于 2019-03-25 01:46:23
一种不使用线程的方法可能看起来像这样:
import os, subprocess, tempfile
def get_first_outfile(inputFileName):
p1_stdout = tempfile.NamedTemporaryFile()
p2_stdout = tempfile.NamedTemporaryFile()
p1 = subprocess.Popen(['process-one', inputFileName], stdout=p1_stdout)
p2 = subprocess.Popen(['process-two', inputFileName], stdout=p2_stdout)
while True:
if p1.poll() is not None: # Process 1 finished first
(file_keep, file_kill) = p1_stdout, p2_stdout
(proc_keep, proc_kill) = p1, p2
break
if p2.poll() is not None: # Process 2 finished first
(file_keep, file_kill) = p2_stdout, p1_stdout
(proc_keep, proc_kill) = p2, p1
break
time.sleep(0.1) # Wait to poll again
proc_kill.terminate() # Terminate the process that didn't finish
file_keep.seek(0) # Rewind the output file we want to keep to the beginning
file_kill.close() # closing a tempfile deletes it
if finished_first.returncode != 0:
raise Exception("Process failed with status %r" % finished_first.returncode)
return keep_outfile # Return the output file we want to keep或者,可以让Python调用shell并在那里执行工作:
shellScript = '''
outOne=$(mktemp -t out.XXXXXX) || exit
outTwo=$(mktemp -t out.XXXXXX) || exit
processOne "$@" >"$outOne" & proc1_pid=$!
processTwo "$@" >"$outTwo" & proc2_pid=$!
wait -n # wait for one of the two processes to finish
if kill -0 "$proc1_pid"; then
# proc1 is still running, so proc2 finished
cat -- "$outTwo"
kill "$proc1_pid"
else
cat -- "$outOne"
kill "$proc2_pid"
fi
'''
def get_output_from_first_process(inputFileName):
return subprocess.check_output(['bash', '-c', shellScript, '_', inputFileName],
stdout=subprocess.PIPE)注意,我们仍然没有使用os.system(),也没有使用shell=True:wait -n是一个bash扩展,所以我们需要确保它可以使用bash,而不是/bin/sh。
https://stackoverflow.com/questions/55326528
复制相似问题