[英]Can I make parallel requests with PyQt5's QThread?
我有一個代碼,可以使我的請求更快。 現在,我需要在PyQt5中運行類似的代碼而不阻塞主程序。 QThread可以解決這個問題嗎?
這是我用ThreadPoolExecutor編寫之前的代碼:
def analyze(self):
if not os.path.exists('input.avi'):
return
self.results = []
with PoolExecutor(max_workers=100) as executor:
for _ in executor.map(self.post, self.images):
pass
if len(self.results) > 0:
self.results.sort()
print(self.results)
def post(self, imageWithID):
if len(self.images) == 0:
return
if self.subscription_key is None or self.subscription_key == '':
return
self.results = []
errors = 0
id, image = imageWithID[0], imageWithID[1]
image2 = image.copy()
bytedata = cv2.imencode('.jpg', image2)[1].tostring()
while errors < 3:
response = requests.post(self.face_api_url,
params=self.params,
headers=self.headers,
data=bytedata).json()
if 'error' in response:
errors += 1
if response['error']['code'] == '429':
print(tup[0], 'sleeping...')
time.sleep(
int(response['error']['message'].split(' ')[-2]))
else:
time.sleep(0.1)
else:
break
self.results.append((id, image, response))
是否可以使用QThread做到這一點(我的意思是使用多線程QThread,而不是單線程以提高速度),因此它不會凍結我認為的主體程序。
我自己解決了我的問題。 這是我完整的QThread代碼。
class analyzingThread(QThread):
i = 0
pause = False
sync = PyQt5.QtCore.QMutex()
pauseCond = PyQt5.QtCore.QWaitCondition()
images = []
results = []
subscription_key = 'MY_SUPER_SECRET_AZURE_API_KEY'
face_api_url = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect'
headers = {'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key': subscription_key
}
params = {
'returnFaceId': 'false',
'returnFaceLandmarks': 'false',
'returnFaceAttributes': 'emotion'}
def resume(self):
self.sync.lock()
self.pause = False
self.sync.unlock()
self.pauseCond.wakeAll()
def pausem(self):
self.sync.lock()
self.pause = True
self.sync.unlock()
def post(self, imageWithId):
errors = 0
id, img = imageWithId[0], imageWithId[1]
bytedata = cv2.imencode('.jpg', img)[1].tostring()
while errors < 3:
response = requests.post(self.face_api_url,
params=self.params,
headers=self.headers,
data=bytedata).json()
if 'error' in response:
errors += 1
if response['error']['code'] == '429':
print(imageWithId[0], 'sleeping...')
time.sleep(
int(response['error']['message'].split(' ')[-2]))
else:
time.sleep(0.1)
else:
break
self.results.append((id, img, response))
def concrrPost(self):
if len(self.images) == 0:
print('no images')
return
with PoolExecutor(max_workers=100) as executor:
for _ in executor.map(self.post, self.images):
pass
self.results.sort()
def run(self):
while True:
self.sync.lock()
if self.pause:
self.pauseCond.wait(self.sync)
self.sync.unlock()
self.concrrPost()
print('-DONE-')
# print(self.results)
self.pausem()
比我用qpushbuttons連接pausem和resume方法:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.