Python SimpleHTTPRequestHandler以异步播放声音
我不知道如何让这个小型http服务器响应get请求并并行播放声音 当前代码不会关闭get请求,直到声音“winsound.PlaySound(“SystemExit”,winsound.SND_别名)”结束播放 我需要的是声音与请求异步,以便get请求尽快结束,声音继续播放Python SimpleHTTPRequestHandler以异步播放声音,python,winsound,simplehttprequesthandler,Python,Winsound,Simplehttprequesthandler,我不知道如何让这个小型http服务器响应get请求并并行播放声音 当前代码不会关闭get请求,直到声音“winsound.PlaySound(“SystemExit”,winsound.SND_别名)”结束播放 我需要的是声音与请求异步,以便get请求尽快结束,声音继续播放 #!/usr/bin/env python3 from http.server import HTTPServer, SimpleHTTPRequestHandler, test import socketserver f
#!/usr/bin/env python3
from http.server import HTTPServer, SimpleHTTPRequestHandler, test
import socketserver
from urllib.parse import urlparse
from urllib.parse import parse_qs
import sys
import winsound
class MyHttpRequestHandler(SimpleHTTPRequestHandler):
try:
def do_GET(self):
# Sending an '200 OK' response
self.send_response(200)
# Setting the header
self.send_header("Content-type", "text/html")
# Whenever using 'send_header', you also have to call 'end_headers'
self.end_headers()
html = "ok"
# Writing the HTML contents with UTF-8
self.wfile.write(bytes(html, "utf8"))
winsound.PlaySound("SystemExit", winsound.SND_ALIAS)
return
except Exception as e:
print(str(e))
# Create an object of the above class
handler_object = MyHttpRequestHandler
PORT = 8000
my_server = socketserver.TCPServer(("", PORT), handler_object)
# Star the server
my_server.serve_forever()
背景 所以基本上,这是关于Python中执行范围的问题。回到上面的代码,为了完成请求,必须执行所有任务
- 发送响应(此响应无效,因为您必须从get方法返回结果)
- 设置标题
- 演奏音乐
asyncio
(这是一个非常方便的lib,请查看)
使用以下命令异步运行:
winsound.PlaySound("SystemExit", winsound.SND_ALIAS|winsound.SND_ASYNC)
如果希望更严格地控制,请使用concurrent.futures.ThreadPoolExecutor()
在其他线程中运行它:
from concurrent.futures import ThreadPoolExecutor
import winsound
pool = ThreadPoolExecutor()
class MyHttpRequestHandler(SimpleHTTPRequestHandler):
try:
def do_GET(self):
# Sending an '200 OK' response
self.send_response(200)
# Setting the header
self.send_header("Content-type", "text/html")
# Whenever using 'send_header', you also have to call 'end_headers'
self.end_headers()
html = "ok"
# Writing the HTML contents with UTF-8
self.wfile.write(bytes(html, "utf8"))
pool.submit(winsound.PlaySound, "SystemExit", winsound.SND_ALIAS)
return
except Exception as e:
print(str(e))
它对我不起作用,测试了你的代码,直接粘贴它,不起作用work@user8459020有失败或例外吗?或者声音根本不起作用,它什么都不起作用。。甚至没有回复GET请求..@user8459020上面的更新代码,只是一个小的输入错误
from concurrent.futures import ThreadPoolExecutor
import winsound
pool = ThreadPoolExecutor()
class MyHttpRequestHandler(SimpleHTTPRequestHandler):
try:
def do_GET(self):
# Sending an '200 OK' response
self.send_response(200)
# Setting the header
self.send_header("Content-type", "text/html")
# Whenever using 'send_header', you also have to call 'end_headers'
self.end_headers()
html = "ok"
# Writing the HTML contents with UTF-8
self.wfile.write(bytes(html, "utf8"))
pool.submit(winsound.PlaySound, "SystemExit", winsound.SND_ALIAS)
return
except Exception as e:
print(str(e))