[英]Python subprocess.check_output hangs when executed from thread
我希望從一些需要一些時間執行的 gcloud 命令中提取 output。 當使用 subprocess.check_output(cmd, shell=True) 方法獨立調用時,它可以工作。 但是我試圖通過使用線程來加速這個過程。 我不知道/理解為什么調用此方法時線程會卡住。
from threading import Thread, Lock
from queue import Queue
import subprocess
import json
class WorkerThread(Thread):
def __init__(self, thread_id, queue):
super().__init__()
self.queue = queue
self.thread_id = thread_id
def run(self):
print(f'Started thread {self.thread_id}')
while True:
try:
project = self.queue.get(timeout=1)
command = f'gcloud iam service-accounts --project={project} list --format="flattened(email)" | awk \'{{ print $2 }}\' | grep -v ^$'
sa_list = subprocess.check_output(command, shell=True).decode('utf-8').splitlines()
print ('THIS DOES NOT GET PRINTED')
if sa_list:
with lock:
data[project] = []
for sa in sa_list:
data[project].append({'email': sa})
self.queue.task_done()
except:
return
data = {}
q = Queue()
threads = []
lock = Lock()
command = 'gcloud projects list --format="flattened(projectId)" | awk \'{ print $2 }\' | grep -v ^$'
projects = subprocess.check_output(command, shell=True).decode('utf-8').splitlines()
for project in projects:
q.put(project)
for i in range(10):
t = WorkerThread(i, q)
t.daemon = True
t.start()
threads.append(t)
q.join()
for t in threads:
t.join()
with open('results_threading', 'w') as f:
json.dump(data, f, indent=2)
我試圖在線程內執行其他代碼(而不是 subprocess.check_output),並且程序似乎同時運行。
還發現了與同一問題相關的舊帖子。 不幸的是,作者似乎找到了解決方案,但沒有提供任何細節。
感謝任何建議。謝謝!
我發現這有什么問題。 線程掛起是因為對於某些命令,output 為空。 這是因為我使用grep -v ^$來過濾空行。 我加了|| 最后為true ,這使得退出代碼為 0 而不是 -1,從而允許線程完成作業並從隊列中獲取下一個作業。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.