Home > Back-end >  How to correctly use args in thread syntax python?
How to correctly use args in thread syntax python?

Time:02-21

Full code:

from code import InteractiveConsole
from turtle import position
import cv2 as cv
from time import time
from windowcapture import WindowCapture
from vision import Vision
import pyautogui
from paths import Products
from time import sleep
from functions import click
from threading import Thread

def do_Collect(self, cord_produto=None, produto=None):
bot_running = True
print(produto)
print(type(produto))
if produto == 'trigo':
    bot_status = produto
    for cord in cord_produto:
        offset_x = 0
        offset_y = 0
        cord_x = cord[0]   offset_x
        cord_y = cord[1]   offset_y
        print(f' Colhendo {produto} nas cordenadas: {cord}')
        print(f'Quantidade de cordadenas encontradas {len(cord_produto)}')
        click(cord_x , cord_y)
    sleep(2)
# else:
#     raise Exception('!Exceção! Produto: {produto} e Cordenadas: {cord_produto}')
bot_running = False
bot_status = None        
###

while(True):
    screenshot = wincap.get_screenshot() #PyAutoGui Tira o ScreenShot
    positions_trigo = vision_Trigo.find(screenshot, 0.6, 'rectangles') 

    ###
    #Bot Commands Call
    if not bot_running:
        print('bot parado')
        if len(positions_trigo):
            trigo = 'trigo'
            t = Thread(target=do_Collect, args=(positions_trigo, trigo))
            t.start()
    positions_trigo = ''
    ###
    
    #Print FPS
    print('FPS: {}'.format(1/(time()-loop_time)))
    loop_time = time()
    
    #Wait Key Q
    if cv.waitKey(1) == ord('q'): #Espera a tecla Q ser apertada para sair
        cv.destroyAllWindows()
        break
    
print('Programa Finalizado')

On "trigo" inside Thread function its my problem. I m trying to pass more than 1 argument to the function *args from thread.

t = Thread(target=do_Collect, args=(positions_trigo, trigo)) #Does not work

If i do without "trigo", it works.

t = Thread(target=do_Collect, args=(positions_trigo,)) #Work

When i test the variable of my callable function, i only receive the standard value "None". So the function below is never True.

def do_Collect(self, cord_produto=None, produto=None):
bot_running = True
print(produto)
print(type(produto))
if produto == 'trigo': #always false

What do i need to correct this?

CodePudding user response:

Your method declaration includes a self, but it's not contained in a class. It will likely work if you remove self.

Please create a MRE next time, i.e. an example which reproduces the problem with a minimum amount of code, like so:

def do_Collect(self, cord_produto=None, produto=None):
    print(cord_produto, produto)

from threading import Thread
t = Thread(target=do_Collect, args=("a", "b"))
t.start()
t.join()

Remove self and it works.

  • Related