0

Python Webserver executable not work only. Pyinstaller build command with --noconsole --onefile.

from http.server import BaseHTTPRequestHandler, HTTPServer
import time
import json

hostName = "127.0.0.1"
serverPort = 8888

class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/data':
            info = "Response data..."
            self.send_response(200)
            self.send_header("Access-Control-Allow-Origin", "*")
            self.send_header("Access-Control-Allow-Methods", "*")
            self.send_header("Access-Control-Expose-Headers", "x-my-custom")
            self.send_header("Content-type", "application/json")
            self.end_headers()
            self.wfile.write(bytes(info, 'utf-8'))

if __name__ == "__main__":        
    webServer = HTTPServer((hostName, serverPort), MyServer)
    print("Server started http://%s:%s" % (hostName, serverPort))

    try:
        webServer.serve_forever()
    except KeyboardInterrupt:
        pass

    webServer.server_close()
    print("Server stopped.")

I want to run my executable webserver on windows without window console.

  • What do you mean it doesn't work? Does it show an error message? – Alexander Feb 02 '23 at 05:04
  • It starts without console, background process exists, but webserver is not responding. If, instead, I compile it normally with the console active, process starts with console window and the web server responds. (I currently use a trick to launch it without a console. I run compiled executable with a vbs script and the vbs script hides the console...) – jfrusciantello Feb 02 '23 at 07:45
  • I had the same problem, but I don't like to show the console at startup. Try disabling the log, like suggested in this response: https://stackoverflow.com/a/3389505/2783173 For me worked fine. – Zompa Mar 29 '23 at 08:43

1 Answers1

1

The solution is to override the log_message method of BaseHTTPRequestHandler as recommended by the documentation:

Logs an arbitrary message to sys.stderr. This is typically overridden to create custom error logging mechanisms.

The reason is explained well in this Playwright issue:

Pyinstaller can be used to package applications in two forms:

  1. Console application. Console window created and output can be written to sys.stdout, sys.stderr

  2. Windowed application. No console created, only a GUI window. No sys.stdout or sys.stderr.

If a 'windowed' application is created, an exception occurs in Playwright as it tries to access stderr but this does not exist.

kym
  • 818
  • 7
  • 12