我想知道我是否可以打印一些每个线程独有的东西,所以就像每个print语句中的一个数字一样,告诉它正在形成哪个线程。这是我的线程实现:
import requests
import time
import threading
import json
from classes.logger import Logger
from classes.cart import Cart
from classes.captcha import Captcha
from classes.queue import Queue
from classes.tools import Tools
if __name__ == '__main__':
session = requests.Session()
lock = threading.Lock()
tools = Tools()
config = tools.load('config/config.json')
log = Logger().log
q = Queue()
cart = Cart(session, lock)
api_key = config['key']['2captcha']
captcha = Captcha(api_key)
queue = Queue()
# Small, Medium, Large, one size
t1 = threading.Thread(target=cart.add_to_cart, args=(['carabiner','palace','silver'],'one size'))
t2 = threading.Thread(target=cart.add_to_cart, args=(['t-shirt','palace','bong'],'small'))
t1.start()
t2.start()
t1.join()
t2.join()
cart.check_cart()
add_to_cart方法:
class Cart:
def add_to_cart(self,keywords,size):
print("blah blah blah")
是否可以打印如下内容:
"1 - blah blah blah"
"2 - blah blah blah"
答案 0 :(得分:2)
我能想到两种方式,1:
您可以简单地将ID参数传递给您的线程,如此
t1 = threading.Thread(target=cart.add_to_cart, args=(['carabiner','palace','silver'],'one size', '1'))
class Cart:
def add_to_cart(self,keywords,size, id):
print(id + "- blah blah blah")
或2,如果您计划启动多个主题并且不想对所有主题进行身份识别,请使用thread.get_ident()值。
class Cart:
def add_to_cart(self,keywords,size):
print(threading.get_ident() + "- blah blah blah")