Python return value from scheduled event

流过昼夜 提交于 2020-06-12 07:47:21

问题


I would like to get the value returned from a function called by a scheduled event. Below is a simple example of what I would like to do.

import time
import sched

schedule = sched.scheduler(time.time, time.sleep)

def ret_this():
    return "This."

def schedthis():
    schedule.enter(2,1,ret_this, ())
    schedule.run()
    ## <- print returned value here

if __name__ == "__main__":
    schedthis()

I have tried many things like:

     schedule.enter(2,1,print ret_this, ())

or even:

    schedule.enter(2,1,ret = ret_this, ())
    schedule.run()
    print ret


Maybe some background will be necessary.

I would like to create a server that will listen for incoming connections(This is done.). When a connection is established a new thread will spawn and the socket will be parsed to that thread. On that thread the values sent to the server will be read and the server will judge what the client is trying to schedule. Once the server knows what the client wants it will schedule it.

If the user wants to view the information after the scheduled event has completed (Where this answer comes in) then it will wait until the event has ended and send the returned values to the client.

If not the the event will be scheduled and the client will receive "Done, farewell." and the connection will close.

I call the programming gods, please could you help me.


回答1:


The problem is actually prety simple. You're returning something from the ret_this function, but you didn't put it anywhere, nor printing it!

Edit
Please see this

Turns out that the code i posted earlier only executes the function, not when it's run by the scheduler. Since scheduler.run only runs a function without actually care about the value it returns, you'll have to store it somewhere to actually know when it's called.

For example, in a global variable:

def ret_this():
    global result
    result = "I'm called!"

Or just print it from ret_this:

def ret_this():
    print "This."

Edit 2
Another way to store it is writing it in a file. You can read it again later:

def ret_this():
    with open('output.txt', 'w') as f:
        f.write('I am called!')

if __name__ = "__main__":
    schedthis()
    with open("output.txt", 'r') as f:
        print(f.read())

If the execution was succesful, your file will contain I am called!. Else, it will be empty.

Hope this helps!



来源:https://stackoverflow.com/questions/19679798/python-return-value-from-scheduled-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!