python直接呼叫ffmpeg

2021-10-04 12:08:02 字數 2181 閱讀 5732

ffmpeg是乙個強大的開源命令列多**處理工具。關於ffmpeg的安裝問題,可以看之前發的《ffmpeg的安裝和簡單使用》。ffmpeg如此強大,那麼能不能用python呼叫並實現它的所有功能呢,答案自然是肯定的。

要實現在python中呼叫ffmpeg,需要了解一下subprocess模組。簡單來說,subprocess模組就相當於乙個包殼的命令列,原則上可以在命令列中實現的事情都可以使用subprocess在python中實現。ffmpeg的呼叫當然不在話下。

最簡單的使用:

import subprocess

subprocess.popen(

, shell=

true

)

上面的**實現了python內使用ffmpeg抓屏的功能,主要使用了subprocess的popen類。

該類第乙個引數是要輸入的命令,和你在cmd命令列或powershell中輸入的完全一樣,要用引號括起來(是乙個字串)"d:\python_work\jamtools/bin/ffmpeg"是我的ffmpeg的路徑,如果你已經把ffmpeg新增進了系統環境變數,可以直接用ffmpeg代替;

然後第二個引數shell=true,表示可以在python的命令列中看到輸出;

這樣寫的時候,你會發現一執行就開始錄屏了!而且,停止不了??!

別急,我們先複習一下,ffmpeg在普通命令列中是怎麼中止的,是直接按鍵盤上的『q』鍵對不對(直接x掉命令列的當我沒說( ̄▽ ̄)")。有沒有辦法在subprocess裡實現接受使用者輸入呢,當然是可以的!

要在subprocess接受使用者輸入,就需要用到subprocess的pipe(管道)了,pipe是什麼可以先了解一下,不了解也無所謂(會用就行)。如果說subprocess是乙個包殼的命令列,pipe就相當於這個命令列的輸入(鍵盤)、輸出(顯示)。

話不多說,直接上**:

import subprocess

import time

ffmpeger=subprocess.popen(

, shell=

true

, stdin=subprocess.pipe)

time.sleep(2)

ffmpeger.stdin.write(

'q'.encode(

"gbk"))

ffmpeger.communicate(

)

上述**把popen類例項化為ffmpeger物件,執行後錄屏2秒後,將通過subprocess的pipe(例項化為stdin)輸入q停止錄屏。

subprocess的pipe還可以實現把命令列中的輸出讀取出來,這在ffmpeg執行分析中非常重要,例如使用ffmpeg列取裝置時我們可以用

然後通過它的輸出來得知裝置名稱等。subprocess中可以通過管道的stderr介面獲得上圖中命令列的輸出,分析即可得到裝置名稱!

例:

ffmpeger=subprocess.popen(

'"d:\python_work\jamtools/bin/ffmpeg" -list_devices true -f dshow -i dummy'

, shell=

true

, stdin=subprocess.pipe,stderr=subprocess.pipe, encoding=

'utf-8'

)

relog = ffmpeger.stderr.read(

)print

(relog)

其中我們通過stderr.read()把輸出(格式為字串)存在relog中,就可以通過普通的字串分析獲取輸出內容了。

macos版本

ubuntu版本

jamtools的github專案位址

performSelector與直接呼叫的區別

performselector與直接呼叫的區別 1 直接呼叫 delegate image self didfinishwithimage image 2 使用 performselector呼叫 delegate performselector selector image didfinishwi...

iOS 應用直接呼叫

1 在plist檔案中,註冊對外介面 滑鼠右擊information property list 然後從列表中選擇url types 右擊 add row 新增乙個物件 item 右擊item add row 從列表中選擇 url schemes 再右擊新增乙個物件 item1 plist如下圖所示...

performSelector呼叫和直接呼叫

下面兩段 都在主線程中執行,我們在看別人 時會發現有時會直接呼叫,有時會利用performselector呼叫,今天看到有人在問這個問題,我便做一下總結,delegateimage self didfinishwithimage image delegate performselector sele...