Reputation: 77
I'm new to Python and I'm having some issues with asynchronous calls and webservers.
I have a SimpleHTTPServer communicating via AJAX with a website that lets you start and stop a service in the host.
The problem is that I don't get my HTTP:201 until the call has ended, which never happens since this is a long running process.
I have tried with call, having my cmd inside a shell script that executes 'cmd &' also tried with Popen, which I though is was non-blocking.
I also tried with thread.start_new_thread(os.system, (cmd,))
def do_POST(self):
# ... some code to get args ...
subprocess.Popen([cmd, args])
# I'd like 'cmd args' to run in the server while I return my HTTP:201 here
self.send_response(201)
self.end_headers()
self.wfile.write(output)
Upvotes: 0
Views: 737
Reputation: 77
I found the solution here:
Why does a background task block the response in SimpleHTTPServer?
def do_POST(self):
# ... some code to get args ... and output ...
subprocess.Popen([cmd, args])
self.send_response(201)
self.send_header("Content-Length", str(len(output))) # This line does the trick!
self.end_headers()
self.wfile.write(output)
Else python holds the TCP connection open until the background command finishes. Specifying the length of your response, python send the TCP FIN and your browser can carry on with its life :)
Upvotes: 0
Reputation: 7852
subprocess.Popen
will run at the same time as your code, which means that you've left out something important in your example.
def demo():
p = subprocess.Popen(['/bin/sleep', '2'])
n = 0
while p.poll() is None:
n+=1
return n
print demo() # prints 1171552 on my machine...
Which means that python spun around that while loop 1171552 times before /bin/sleep
exited.
Upvotes: 1