To make your asynchronous code, you must use Twisted Deferreds as described here . Deferrals give you an API to execute asynchronous code, they allow you to attach callbacks to your functions, and they execute code in a Twisted event loop controlled by a reactor object.
I see two possible ways to use Deferred in your case.
1) Running a task in the background using reactor.callLater()
This is normal if the dostuff handler dostuff not care about the result. You can use reactor.callLater () . This way your async function will execute after returning the value from dostuff .
So something like this:
from klein import run, route, Klein from twisted.internet import defer, task, reactor import os app = Klein() def logging(data): ofile = open("file", "w") ofile.write(data) result = os.system("ls") print(result) @route('/') def dostuff(request): reactor.callLater(0, logging, "some data") print("check!") return b'Hello, world!' run("localhost", 8080)
The order of events with this code is as follows, first a "check" is printed, then the response "hello world" is returned and, finally, the async call ends and prints the results of running os.system() .
2016-08-11 08:52:33+0200 [-] check! 2016-08-11 08:52:33+0200 [-] "127.0.0.1" - - [11/Aug/2016:06:52:32 +0000] "GET / HTTP/1.1" 200 13 "-" "curl/7.35.0" a.py file
2) Run the task in the background and get the result using task.deferLater()
If you care about the results of your registration function, you can also attach a callback to this object and use the twisted.internet.task API. If you want to go this way, you need to reorganize the handler to work as follows
@route('/') def dostuff(request): def the_end(result): print("executed at the end with result: {}".format(result)) dfd = task.deferLater(reactor, 0, logging, "some data") dfd.addCallback(the_end) print("check!") return b'Hello, world!'
Thus, the order of events will be the same as above, but the_end function will be executed at the end after the logging function completes.
2016-08-11 08:59:24+0200 [-] check! 2016-08-11 08:59:24+0200 [-] "127.0.0.1" - - [11/Aug/2016:06:59:23 +0000] "GET / HTTP/1.1" 200 13 "-" "curl/7.35.0" a.py file 2016-08-11 08:59:24+0200 [-] executed at the end with result: some result