python - 在线程上调用时,Python函数无法开始执行

标签 python python-3.x multithreading

我正在制作一个简单的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_messageConnect,既不调用也不返回它们。因此实际上您的线程在启动后就立即结束,什么也不做,这就是为什么它不打印任何内容的原因。
您可以做的最简单的事情是:

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/

相关文章:

java - AtomicInteger 的嵌套方法调用在 java 中也是原子的吗

Python:通过函数传递参数

python - tensorflow 属性错误initialize_all_variables

python-3.x - sqlite3 python3,数据库的用户输入

python - Centos Python 3 : ConfigParser using environment variables and cross references

java - 理论上是否可以使用静态分析工具证明Java代码不存在竞争条件?

c++ - 我可以在单读/单写队列中用 volatile 替换原子吗?

python - 关于 Pytorch 中的奇数图像尺寸

python - 我的learning_rate真的在theano中改变了吗?

正则表达式提取首字母缩略词