Python脚本在启动线程时被杀死
我有一个字典,其中2000个键值对key作为应用程序的URL,value作为命令来执行应用程序的测试用例 我需要使用线程并行执行这些任务,并使用子进程模块启动测试用例命令 在运行一些线程并在std out中获得输出后,后续线程被卡住并失败 我尝试通过在代码中切掉500个队列项进行检查。它不会被击中,也会收到带有测试用例输出报告的邮件 请告诉我如何避免线在中间扭动 我的代码是Python脚本在启动线程时被杀死,python,multithreading,unit-testing,subprocess,python-multithreading,Python,Multithreading,Unit Testing,Subprocess,Python Multithreading,我有一个字典,其中2000个键值对key作为应用程序的URL,value作为命令来执行应用程序的测试用例 我需要使用线程并行执行这些任务,并使用子进程模块启动测试用例命令 在运行一些线程并在std out中获得输出后,后续线程被卡住并失败 我尝试通过在代码中切掉500个队列项进行检查。它不会被击中,也会收到带有测试用例输出报告的邮件 请告诉我如何避免线在中间扭动 我的代码是 import Queue import subprocess from threading import Thread S
import Queue
import subprocess
from threading import Thread
SERVER_COMMANDS = {}
TOTAL_OUTPUT = []
def run_function(server_commands, receivers, url, test_case_name, mail_send=True):
threads = []
q_items = []
counter = 0
for server, command in server_commands.iteritems():
q_items.append(dict(counter=counter,server=server, command=command, server_commands=server_commands))
counter += 1
Q = Queue.Queue()
for item in q_items:
Q.put(item)
for i in xrange(90):
th = Thread(target=_run_function, args=(Q,))
th.start()
threads.append(th)
for th in threads:
th.join()
total_output = ''.join(TOTAL_OUTPUT)
def _run_function(q):
while not q.empty():
args = q.get()
server = args.get('server')
command = args.get('command')
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
process.wait()
output, error = process.communicate()
print "The thread number is %s" % args.get('counter')
SERVER_COMMANDS[server] = output
TOTAL_OUTPUT.append(output)
for line in output:
sys.stdout.write(line)
要获得更好的视图,请检查一个问题是,您在
q.empty()
和q.get()
之间存在竞争条件。如果另一个线程获得这两个调用之间的最后一项,该线程将阻塞。您应该放弃对q.empty()
的调用,改为调用。然后,当它引发Empty
异常时,退出该函数
但是,我怀疑您真正的问题是在process.communicate()之前调用process.wait()
。从:
警告这将在使用stdout=PIPE
和/或stderr=PIPE
时死锁,并且子进程生成足够的输出到管道,从而阻止等待OS管道缓冲区接受更多数据。使用communicate()
来避免这种情况
停止调用process.wait()
您还可能会发现比启动自己的更容易。一个问题是,您在q.empty()
和q.get()
之间存在竞争条件。如果另一个线程获得这两个调用之间的最后一项,该线程将阻塞。您应该放弃对q.empty()
的调用,改为调用。然后,当它引发Empty
异常时,退出该函数
但是,我怀疑您真正的问题是在process.communicate()之前调用process.wait()
。从:
警告这将在使用stdout=PIPE
和/或stderr=PIPE
时死锁,并且子进程生成足够的输出到管道,从而阻止等待OS管道缓冲区接受更多数据。使用communicate()
来避免这种情况
停止调用process.wait()
您也可能会发现,这比启动自己的更容易。谢谢。通过将timeout参数指定给q.get(timeout=10),我克服了threadsthank中的挂起问题。通过将timeout参数指定给q.get(timeout=10),我克服了线程中的挂起问题