pyinstaller 打包无窗口python http.server无法启动
pyinstaller 打包无窗口python http.server无法启动
最近在写一个简单的文件服务器用来访问静态文件,遇到在pyinstaller无窗口模式下无法启动的问题,记录一下解决方案。
-
原因:http.server需要将记录输出到窗口,而pyinstaller打包无窗口模式没有地方输出
class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): ... def log_message(self, format, *args): """Log an arbitrary message. This is used by all other logging functions. Override it if you have specific logging wishes. The first argument, FORMAT, is a format string for the message to be logged. If the format string contains any % escapes requiring parameters, they should be specified as subsequent arguments (it's just like printf!). The client ip and current date/time are prefixed to every message. Unicode control characters are replaced with escaped hex before writing the output to stderr. """ message = format % args sys.stderr.write("%s - - [%s] %s\n" % (self.address_string(), self.log_date_time_string(), message.translate(self._control_char_table)))
-
解决方案1:
import os import http.server import socketserver DIRECTORY = os.path.join(os.path.abspath(os.path.dirname(__file__)), "static", "js") PORT = 38121 class SimpleHTTPRequestHandlerWithDirectory(http.server.SimpleHTTPRequestHandler): def __init__(self, *args, **kwargs): super().__init__(*args, directory=DIRECTORY, **kwargs) # 重写这个防止服务打包后起不来 def log_message(self, format, *args): pass def run_server(port=PORT): # 创建并启动服务器 try: with socketserver.TCPServer(("", port), SimpleHTTPRequestHandlerWithDirectory) as httpd: # print("Serving at port", port) httpd.serve_forever() except OSError as e: print(e) pass if __name__ == '__main__': run_server()
-
解决方案2:
import os import http.server import socketserver DIRECTORY = os.path.join(os.path.abspath(os.path.dirname(__file__)), "static", "js") PORT = 38121 class SimpleHTTPRequestHandlerWithDirectory(http.server.SimpleHTTPRequestHandler): def __init__(self, *args, **kwargs): super().__init__(*args, directory=DIRECTORY, **kwargs) def run_server(port=PORT): # 创建并启动服务器 try: with socketserver.TCPServer(("", port), SimpleHTTPRequestHandlerWithDirectory) as httpd: # print("Serving at port", port) httpd.serve_forever() except OSError as e: print(e) pass if __name__ == '__main__': import sys if sys.stdout is None: sys.stdout = open(os.devnull, "w") if sys.stderr is None: sys.stderr = open(os.devnull, "w") run_server()
-
解决方案3
https://pyinstaller.org/en/stable/spec-files.html#specifying-python-interpreter-options
此时此刻,非我莫属