Resumo : neste tutorial, você aprenderá como retornar valores de um thread filho para o thread principal estendendo a threading.Thread
classe.
Quando um programa Python é iniciado, ele possui um único thread chamado thread principal . Às vezes, você deseja descarregar tarefas de E/S para novos threads e executá-las simultaneamente. Além disso, você também pode obter os valores de retorno desses threads no thread principal.
Para retornar um valor de um thread, você pode estender a classe Thread e armazenar esse valor na instância da classe.
O exemplo a seguir ilustra como verificar um URL especificado e retornar seu código de status HTTP em um thread separado:
from threading import Thread
import urllib.request
class HttpRequestThread(Thread):
def __init__(self, url: str) -> None:
super().__init__()
self.url = url
self.http_status_code = None
self.reason = None
def run(self) -> None:
try:
response = urllib.request.urlopen(self.url)
self.http_status_code = response.code
except urllib.error.HTTPError as e:
self.http_status_code = e.code
except urllib.error.URLError as e:
self.reason = e.reason
def main() -> None:
urls = [
'https://httpstat.us/200',
'https://httpstat.us/400'
]
# create new threads
threads = [HttpRequestThread(url) for url in urls]
# start the threads
[t.start() for t in threads]
# wait for the threads to complete
[t.join() for t in threads]
# display the URLs with HTTP status codes
[print(f'{t.url}: {t.http_status_code}') for t in threads]
if __name__ == '__main__':
main()
def main() -> None:
urls = [
'https://httpstat.us/200',
'https://httpstat.us/400'
]
# create new threads
threads = [HttpRequestThread(url) for url in urls]
# start the threads
[t.start() for t in threads]
# wait for the threads to complete
[t.join() for t in threads]
# display the URLs with HTTP status codes
[print(f'{t.url}: {t.http_status_code}') for t in threads]
Linguagem de código: Python ( python )
Saída:
ttps://httpstat.us/200: 200
https://httpstat.us/400: 400
Linguagem de código: Python ( python )
Como funciona.
Primeiro, defina a HttpRequestThread
classe que estende a Thread
classe:
class HttpRequestThread(Thread):
# ...
Linguagem de código: Python ( python )
Segundo, defina o
método que aceita uma URL. Dentro do __init__()
método adiciona variáveis __init__()
url
,
e http_status_code
reason
de instância. O
irá armazenar o código de status do http_status_code
url
no momento da verificação e reason
armazenará a mensagem de erro caso ocorra um erro:
def __init__(self, url: str) -> None:
super().__init__()
self.url = url
self.http_status_code = None
self.reason = None
Linguagem de código: Python ( python )
Terceiro, substitua o run()
método que usa a urllib
biblioteca para obter o código de status HTTP do URL especificado e atribua-o ao http_status_code
campo. Se ocorrer um erro, atribui a mensagem de erro ao reason
campo:
def run(self) -> None:
try:
response = urllib.request.urlopen(self.url)
self.http_status_code = response.code
except urllib.error.HTTPError as e:
self.http_status_code = e.code
except urllib.error.URLError as e:
self.reason = e.reason
Linguagem de código: Python ( python )
Posteriormente, podemos acessar url
, http_status_code
e reason
a partir da instância da HttpRequestThread
classe.
Quarto, defina a main()
função que cria instâncias da HttpRequestThread
classe, inicia os threads, espera que eles sejam concluídos e obtém o resultado das instâncias:
def main() -> None:
urls = [
'https://httpstat.us/200',
'https://httpstat.us/400'
]
# create new threads
threads = [HttpRequestThread(url) for url in urls]
# start the threads
[t.start() for t in threads]
# wait for the threads to complete
[t.join() for t in threads]
# display the URLs with HTTP status codes
[print(f'{t.url}: {t.http_status_code}') for t in threads]
Linguagem de código: Python ( python )
Resumo
- Estenda a
Thread
classe e defina as variáveis de instância dentro da subclasse para retornar os valores de um thread filho para o thread principal.