Gess1t
Gess1t

Reputation: 81

Pythonw, pyw, & arg, /B won't make python's http-server run in background

I've tried every method in the title to run it in the background but here are the issues i got trying to use them:

pythonw and pyw: server doesn't work, going to localhost:8000 error with ERR_EMPTY_RESPONSE.
& arg and START/B: doesn't start script in background and instead output server log

so now I'm short on ideas on how to run this script in the background.

Upvotes: 2

Views: 708

Answers (2)

ExpressMpeg
ExpressMpeg

Reputation: 1

I have found a good solution for starting an http server in the background.

This solution is a bit of a hack, but it works quite well on my computer.

Use the subprocess module in a separate .pyw file to start the server script stored in a .py file.

launch.pyw

import subprocess

subprocess.run(
            ["python.exe", "http_server.py"], 
            creationflags=0x08000000,         # use this "non creation window" flag if 
                                              # working with pyinstaller
)

http_server.py

import http.server

# your code

if __name__ == "__main__":
    httpd = http.server.HTTPServer(("localhost", 8000), 
            http.server.SimpleHTTPRequestHandler)
    httpd.serve_forever()

Now, you should start your server with launch.pyw script.

Upvotes: 0

simon
simon

Reputation: 5312

Using pythonw, it should help to explicitly redirect stdout and stderr to a file – maybe this behavior is somehow related to the problem described here (although this seems to be specific to Python 2.7). Not capturing the output by redirecting it to os.devnull seems to work as well.

The following script produces a minimum working server example with pythonw for me (using Python 3.7.9):

import http.server
import os
import sys


if __name__ == "__main__":

    sys.stdout = sys.stderr = open(os.devnull, "w")

    httpd = http.server.HTTPServer(("localhost", 8000), http.server.SimpleHTTPRequestHandler)
    httpd.serve_forever()

Upvotes: 4

Related Questions