gpt4 book ai didi

python - 如何获取Timer中使用的函数的输出

转载 作者:行者123 更新时间:2023-12-03 13:02:40 26 4
gpt4 key购买 nike

我正在运行一个flask应用程序,该应用程序每天都应同时调用一个函数getSomething(input)。该函数返回一个字符串。我无法返回print(),因为我需要将字符串传递给另一个函数。

使用定时器功能时t = Timer(secs, getSomething, args=[input])我不知道如何对getSomething函数的返回值进行赋值。

例子:

from datetime import datetime, timedelta
from threading import Timer

# This shall trigger something at a certain time^
x = datetime.today()
y = x + timedelta(seconds=5)
delta_t = y - x
secs = delta_t.seconds + 1

def getSomething(a):
b = a + " Hello World"
return b

s = "Test"
t = Timer(secs, getSomething, args=[s])
t.start()

我知道 here也曾问过同样的问题。但是我无法适应我的问题,尽管我认为我无法避免退货。

最佳答案

该问题可以通过以下方式解决:

from datetime import datetime, timedelta
from threading import Timer

d = [] # use list, dictionary, some class or queue.Queue to store data


def getSomething(a):
global d
d.append(a + " Hello World")


if __name__ == "__main__":
# This shall trigger something at a certain time^
x = datetime.today()
y = x + timedelta(seconds=5)
delta_t = y - x
secs = delta_t.seconds + 1
s = "Test"
t = Timer(secs, getSomething, args=[s])
t.start()
t.join() # need to wait until thread is finished to get new d value
print(d[0])
另一个示例如何从另一个线程获取数据:
from threading import Thread
import time


class Storage:
def __init__(self):
self.storage = ""


class MyThread(Thread):
def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None):
super().__init__(group=group, target=target, name=name, daemon=daemon)
self.args = args
self.kwargs = kwargs

def run(self):
self.args[0].storage += "Hello!"


if __name__ == "__main__":
s = Storage()
branch = MyThread(args=(s,),)
branch.start()
time.sleep(1) # need some time to wait for another thread
print(s.storage)

关于python - 如何获取Timer中使用的函数的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58663953/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com