![](/img/trans.png)
[英]What is the best way to read a file from stdin using bash script and pass the read lines to a python script
[英]bash or python script to read binary data from STDIN and save to a file
在沒有人告訴我之前,我完全意識到我想要做的事情是荒謬的,但是我有我的理由。
我有一台可以在其中編寫腳本(bash或python)的服務器。 該腳本需要接受來自STDIN的二進制數據並將其保存到文件中。 確切地說,二進制數據是WAV文件。
我正在使用的是名為Workflow的iOS應用。 該應用程序將允許我錄制音頻文件,然后將其作為STDIN輸入發送到將通過SSH運行的腳本。 因此,我的腳本需要采用該STDIN輸入並將其保存到文件中。
有什么想法/想法嗎? 我完全不知道該從哪里開始。
要將stdin保存到POSIXy系統上的文件:
copyfileobj()
通常, 如果可以從文件(可os.sendfile()
mmap的文件描述符)重定向stdin (也不適用於您的情況),也可以嘗試os.sendfile()
)。
#!/usr/bin/env python
import os
import shutil
import sys
with os.fdopen(sys.stdin.fileno(), 'rb') as input_file,\
open(sys.argv[1], 'wb') as output_file:
shutil.copyfileobj(input_file, output_file)
例:
$ python -msave_stdin output_file
那應該等同於:
$ cat >| output_file
要從python中的stdin中讀取:
import sys
input = sys.stdin.read()
要將二進制文件寫入文件:
with open('name_of_file_here','wb') as output:
output.write(input)
“ wb”以二進制模式發送寫操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.