[英]open external file through wave.open in python
I'm using wave.open to open file, if i give local path如果我提供本地路径,我正在使用 wave.open 打开文件
async def run_test(uri):
async with websockets.connect(uri) as websocket:
wf = wave.open('test.wav', "rb")
then it is working but if i give external path it is not working那么它正在工作,但如果我给外部路径它不工作
async def run_test(uri):
async with websockets.connect(uri) as websocket:
wf = wave.open('http://localhost:8000/storage/uploads/test.wav', "rb")
getting this error:收到此错误:
OSError: [Errno 22] Invalid argument: 'http://localhost:8000/storage/uploads/test.wav' OSError:[Errno 22] 无效参数:'http://localhost:8000/storage/uploads/test.wav'
Yeah, wave.open()
doesn't know anything about HTTP.是的, wave.open()
对 HTTP 一无所知。
You'll need to download the file first, eg with requests
(or aiohttp
or httpx
since you're in async land).您需要先下载文件,例如使用requests
(或aiohttp
或httpx
,因为您处于异步状态)。
import io, requests, wave
resp = requests.get('http://localhost:8000/storage/uploads/test.wav')
resp.raise_for_status()
bio = io.BytesIO() # file-like memory buffer
bio.write(resp.content) # todo: if file can be large, maybe use streaming
bio.seek(0) # seek to the start of the file
wf = wave.open(bio, "rb") # wave.open accepts file-like objects
This assumes the file is small enough to fit in memory;这假设文件足够小以适合 memory; if it's not, you'd want to use tempfile.NamedTemporaryFile
instead.如果不是,你会想使用tempfile.NamedTemporaryFile
代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.