这是我根据 Nadia 和 Jim 的评论提出的解决方案。我不确定这是否是最好的方法,但它确实有效。被调用的原始子脚本需要是一个 shell 脚本,因为我需要使用一些 3rd 方应用程序,包括 Matlab。所以我不得不把它从 Python 中取出并用 bash 编码。
import sys
import os
import multiprocessing
import subprocess
def work(staname):
print 'Processing station:',staname
print 'Parent process:', os.getppid()
print 'Process id:', os.getpid()
cmd = [ "/bin/bash" "/path/to/executable/create_graphs.sh","--name=%s" % (staname) ]
return subprocess.call(cmd, shell=False)
if __name__ == '__main__':
my_list = [ 'XYZ', 'ABC', 'NYU' ]
my_list.sort()
print my_list
# Get the number of processors available
num_processes = multiprocessing.cpu_count()
threads = []
len_stas = len(my_list)
print "+++ Number of stations to process: %s" % (len_stas)
# run until all the threads are done, and there is no data left
for list_item in my_list:
# if we aren't using all the processors AND there is still data left to
# compute, then spawn another thread
if( len(threads) < num_processes ):
p = multiprocessing.Process(target=work,args=[list_item])
p.start()
print p, p.is_alive()
threads.append(p)
else:
for thread in threads:
if not thread.is_alive():
threads.remove(thread)
这似乎是一个合理的解决方案?我尝试使用 Jim 的 while 循环格式,但我的脚本什么也没返回。我不确定为什么会这样。这是我用 Jim 的“while”循环替换“for”循环运行脚本时的输出:
hostname{me}2% controller.py
['ABC', 'NYU', 'XYZ']
Number of processes: 64
+++ Number of stations to process: 3
hostname{me}3%
当我用“for”循环运行它时,我得到了一些更有意义的东西:
hostname{me}6% controller.py
['ABC', 'NYU', 'XYZ']
Number of processes: 64
+++ Number of stations to process: 3
Processing station: ABC
Parent process: 1056
Process id: 1068
Processing station: NYU
Parent process: 1056
Process id: 1069
Processing station: XYZ
Parent process: 1056
Process id: 1071
hostname{me}7%
所以这行得通,我很高兴。但是,我仍然不明白为什么我不能使用 Jim 的 'while' 样式循环而不是我正在使用的 'for' 循环。感谢所有的帮助 - 我对 @stackoverflow 的知识广度印象深刻。