首页 > 解决方案 > 在线程上调用 Python 函数时不会开始执行

问题描述

我正在制作一个简单的 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开始执行。

谁能帮我解决这个问题?我是否以错误的方式使用线程?提前致谢。

标签: pythonpython-3.xmultithreading

解决方案


您正在将该Run() 函数设置为线程的目标。但是,当您运行该函数时,它所做的只是定义函数process_messageand 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)

我还建议不要使用大写字母作为第一个字符来命名函数,按照惯例(请参阅 pep-8 关于命名约定),这应该保留给类。


推荐阅读