我正在制作一个简单的Python函数,其中有一个在主线程上运行的函数Updater
,该函数现在仅打印某些内容,但它将执行其他任务,并由schedule
调用,而另一个函数我想并行运行,因此,我正在使用线程。
这是我的尝试:
import websocket, json, time, schedule, logging, cfscrape, threading, requests
def Run():
def process_message(ws,msg):
print(msg)
def Connect():
websocket.enableTrace(False)
ws = websocket.WebSocketApp("wss://stream.binance.com/stream?streams=btcusdt@depth", on_message = process_message)
ws.run_forever()
def Updater():
print('Updating..')
threading.Thread(target=Run).start()
schedule.every(1).seconds.do(Updater)
while True:
schedule.run_pending()
time.sleep(1)
我想要做的是让这个脚本使用线程同时并行执行websocket连接和计划的功能。我的代码的问题是Run
没有开始。仅Updater
将开始执行。谁能帮我这个忙吗?我使用线程的方式错误吗?提前致谢。
最佳答案
您正在将Run()
函数设置为线程的目标。但是,当您运行该函数时,它所做的只是定义函数process_message
和Connect
,既不调用也不返回它们。因此实际上您的线程在启动后就立即结束,什么也不做,这就是为什么它不打印任何内容的原因。
您可以做的最简单的事情是:
import websocket, json, time, schedule, logging, cfscrape, threading, requests
def Run():
def process_message(ws,msg):
print(msg)
def Connect():
websocket.enableTrace(False)
ws = websocket.WebSocketApp("wss://stream.binance.com/stream?streams=btcusdt@depth", on_message = process_message)
ws.run_forever()
# no need to call process_message since it will be called automatically by
# the WebSocketApp created by Connect
Connect() # Actually call the Connect function, so that it is used in your thread
def Updater():
print('Updating..')
threading.Thread(target=Run).start()
schedule.every(1).seconds.do(Updater)
while True:
schedule.run_pending()
time.sleep(1)
我也建议不要使用大写字母作为第一个字符来命名函数,因为按照惯例(see pep-8 about naming convention),这应该保留给类。
关于python - 在线程上调用时,Python函数无法开始执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63285009/