python - Python SimpleHTTPRequestHandler 播放声音异步
问题描述
我不知道如何让这个小型 http 服务器回复 get 请求并并行播放声音。
当前代码,直到声音 "winsound.PlaySound("SystemExit", winsound.SND_ALIAS)" 结束播放才关闭获取请求。
我需要的是声音与请求异步,以便获取请求尽快结束并且声音继续播放。
#!/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()
解决方案
使用一个标志来异步运行它:
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))
推荐阅读
- javascript - 如何在不访问儿童点击处理程序和 stopPropagation 调用的情况下停止冒泡?(可点击包装内的可点击组件)
- python - 移动到远程服务器时如何引用本地文件?
- api - 热敏打印机
- database - 如何为存储订单详细信息的关系表建模
- typescript - 有没有办法在 typescript 中为 Azure Functions 自动生成 swagger 文档?
- openmp - OpenMP 实际线程数
- amazon-web-services - Fargate 服务不尊重安全组
- powershell - PowerShell Outlook 显示保存的名称而不是完整的电子邮件地址
- c++ - 如何从 C++ 中的函数内部更改数组
- python - 使用列表理解创建一个二维 numpy 数组