Need help on tornado coroutines - python

I'm new to python and tornado. I was trying some stuff with coroutines.
def doStuff(callback):
def task():
callback("One Second Later")
Timer(1,task).start()
#gen.coroutine
def routine1():
ans = yield gen.Task(doStuff)
raise gen.Return(ans)
if __name__ == "__main__":
print routine1()
I'm trying to get the result of doStuff() function, which I expect to be "One Second Later". But it's not working. Any help would be appreciated. Thank you

What's probably happening is, you haven't started the IOLoop, nor are you waiting for your coroutine to complete before your script exits. You'll probably notice your script runs in a couple milliseconds, rather than pausing for a second as it ought. Do this:
if __name__ == "__main__":
from tornado.ioloop import IOLoop
print IOLoop.instance().run_sync(routine1)

Related

The most proper way to stop event loop after asyncio.run has been called?

Considering the following code:
import asyncio
async def main() -> None:
await asyncio.sleep(2**256)
if __name__ == '__main__':
asyncio.run(main())
What is the most proper way to terminate coroutine main, after it has been called by asyncio.run? When I invoked script and pressed CTRL + C, I saw an ugly traceback.
As I can see from the source code, asyncio.run does a lot of machinery behind the scenes, so I would like to continue using it.
You probably should handle the SIGINT signal.
import asyncio
import functools
import signal
async def main() -> None:
await asyncio.sleep(2**256)
def handler(loop):
...
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.add_signal_handler(signal.SIGINT, functools.partial(handler, loop=loop))
loop.run_until_complete(main())
The question is how the handler should look like? If you want just close program without exception, use sys.exit()
def handler(loop):
sys.exit()
However to close everything gracefully, you need to finish every task and stop the loop. See this topic for more insight.

How to interrupt a thread in python 2?

I've encountered an uninterruptable code in Python 2.7.
from time import sleep
import threading
def fun():
for i in range(100):
print(i)
sleep(0.1)
if __name__ == '__main__':
threading.Timer(1, fun).start()
First, how come it is uninterruptable? (It ignores SIGINT)
In Python 3 this code interrupts fine.
Second, what changes should I make for it to respond to SIGINT before it finishes the loop?
In my actual case, it's an infinite loop :.(
I'm not yet sure why does it happen, but this phenomenon is mentioned in Python 3.2 bug fix report.
I found a workaround by unfolding the following code:
def fun():
while True:
... my code ...
sleep(0.1)
if __name__ == '__main__':
threading.Timer(1, fun).start()
Into:
def fun():
... my code ...
threading.Timer(0.1, fun).start()
if __name__ == '__main__':
threading.Timer(1, fun).start()

How can I make a function run in the background without blocking my entire program?

I have some difficulties into making this function running in the background without blocking my entire program, how can I run that function in loop, without blocking my entire program?
This is the function:
while True:
schedule.run_pending()
Thank you for any reply.
Edit:
def FunctioninLoop():
while True:
schedule.run_pending()
async def MyFunction():
ScheduleToexecute=schedule.every().minute.do(Functionscheduled)
t = Thread(target=FunctioninLoop())
t.start()
print("The execution is going on")
Threads are what you are looking for.
Consider the following code:
from threading import Thread
def myfunc(a, b, c):
pass
# Creates a thread
t = Thread(target=myfunc, args=(1, 2, 3))
# Launches the thread (while not blocking the main execution)
t.start()
somecode
somecode
somecode
# Waits for the thread to return (not a must)
t.join()
Hope I've helped! :)
import threading
pender = threading.thread(schedule.run_pending) # Does not Block
print("life goes on until...")
pender.join() # Blocks until schedule.run_pending() is complete.
You can use python's subprocess module
https://docs.python.org/3.2/library/subprocess.html
import os
def myfunction():
..........
os.spawnl(os.P_NOWAIT, myfunction())

Python threading calls the method multiple times

I have to curl a website and display a message if the header status is not 200. The logic works fine, but I'm facing trouble with calling the method once.
The threading.Time is supposed to call the method ONCE every 20 seconds but apparently, it calls it multiple times. Could someone please tell me how can I make it call the method once every 20 seconds?
import requests
import threading
def check_status(url):
while True:
status = requests.get(url)
if status.status_code != 200:
print('faulty')
def main():
threading.Timer(2.0, check_status, args=('https://www.google.com',)).start()
if __name__ == "__main__":
main()
Just create a new timer after you finish the old one.
import requests
import threading
def check_status(url):
status = requests.get(url)
if status.status_code != 200:
print('faulty')
threading.Timer(2.0, check_status, args=('https://www.google.com',)).start()
def main():
threading.Timer(2.0, check_status, args=('https://www.google.com',)).start()
if __name__ == "__main__":
main()
Every 20 seconds, you are creating a thread that enters an infinite loop which checks the HTTP status. Even if you did not use threading.Time, you would still get multiple prints. Remove the while loop and it will work as you expect.
Update
My mistake, looking at the documentation: https://docs.python.org/2/library/threading.html#timer-objects
Time will execute the function after the time has passed. Then it will exit. What you need to do, is have time.sleep inside the while loop, and call the function just once inside your main.

Python: threading multiple infinite loops at the same time

In Python I am trying to get one infinite loop to start running parallel at the same time, a simple example would be:
from threading import Thread
def func(argument):
while True:
print(argument)
def main():
Thread(target=func("1")).start()
Thread(target=func("2")).start()
Thread(target=func("3")).start()
Thread(target=func("4")).start()
if __name__ == '__main__':
main()
Right now only the first thread runs, so the result is:
1
1
1
1
....
And it should be:
1
2
3
4
....
I found several similar questions but none of the provided solutions seem to work for me, including using join on the threads.
So if anyone knows the solution to my problem it would be very much appreciated.
Thanks in advance!
The first Thread isn't starting. You are calling the func in main and attempting to set its return value as target, but it runs forever and the first Thread never gets created. You want:
from threading import Thread
def func(argument):
while True:
print(argument)
def main():
Thread(target=func,args=("1",)).start()
Thread(target=func,args=("2",)).start()
Thread(target=func,args=("3",)).start()
Thread(target=func,args=("4",)).start()
if __name__ == '__main__':
main()
This will pass func as an object. Starting the thread will call that object with the tuple of args specified.
You can define your own thread:
from threading import Thread
class MyThread(Thread):
def __init__(self,argument, **kwargs):
super(MyThread, self).__init__(**kwargs)
self.argument = argument
def run(self):
while True:
print self.argument
if __name__ == '__main__':
MyThread('1').start()
MyThread('2').start()
MyThread('3').start()
MyThread('4').start()

Categories

Resources