0

我编写了一个简单的 python http 服务器来提供当前工作目录的文件(文件夹)。

import socketserver
http=''
def httpServer(hostIpAddress):
  global  http
  socketserver.TCPServer.allow_reuse_address=True
  try:
    with  socketserver.TCPServer((hostIpAddress,22818),SimpleHTTPRequestHandler) as http:
       print(1123)
       http.serve_forever()
 except Exception as e:
     print(str(e))
       

if __name__ == '__main__':
     httpServer('192.168.1.2')      

此代码按预期工作。它提供内容。但是,当我使用 cx-freeze 冻结它(将 ist 转换为可执行文件)时。它不提供文件 .IN chrome 它输出 ERR_EMPTY_RESPONSE。我尝试了其他浏览器但无济于事。

My setup.py for the freeze is
executables = [
    Executable("test_http.py", base=base,target_name="test_http",shortcutName="test_http",shortcutDir="DesktopFolder")
]

setup(
    name="test_http",
    options={"build_exe":build_exe_option,"bdist_msi":bdist_msi_options},
    executables=executables
    )

.exe 可以正常运行,您甚至可以在任务管理器中看到该程序正在运行。我用过:cx-freeze(我试过 6.6、6.7、6.8 版)python 3.7.7 32 位操作系统:windpows 8.1

提前致谢。

4

1 回答 1

0

我没有使用函数 httpserver ,而是使用了类,它毫无问题地构建了 exe,现在 http 服务器甚至以它的可执行形式运行。

感谢:https ://stackoverflow.com/users/642070/tdelaney提供此解决方案:

https://pastebin.com/KsTmVWRZ

import http.server
import threading
import functools
import time
 
# Example simple http server as thread
 
class SilentHandler(http.server.SimpleHTTPRequestHandler):
    
    def log_message(self, format, *args, **kwargs):
        # do any logging you like there
        pass
    
class MyHttpServerThread(threading.Thread):
    
    def __init__(self, address=("0.0.0.0",8000), target_dir="."):
        super().__init__()
        self.address = address
        self.target_dir = "."
        self.server = http.server.HTTPServer(address, functools.partial(SilentHandler, directory=self.target_dir))
        self.start()
 
    def run(self):
        self.server.serve_forever(poll_interval=1)
 
    def stop(self):
        self.server.shutdown() # don't call from this thread
        
# test  
 
if __name__ == "__main__":
    http_server = MyHttpServerThread()
    time.sleep(10)
    http_server.stop()
    print("done")
于 2021-10-09T21:12:19.517 回答