生成命令行程序使用腳本

場景

最近工做中須要常常使用ffmpeg一類的命令行程序,爲了不過多重複操做,因而思考了下編寫命令程序腳本的幾種方式,包括c#,python,bat,powershell,shell。html

C#

/// <summary>
/// 使用 process 調用程序
/// 對指定視頻轉碼
/// </summary>
private static void Ffmpeg()
{
    using (var p = new Process())
    {
        // 想要運行命令/程序名/程序絕對路徑
        // ffmpeg 已添加至 path
        p.StartInfo.FileName = @"ffmpeg";
        p.StartInfo.Arguments = "-i 1.mp4 -c:v libx264 -c:a aac -y 1.flv";
        // true 就沒法重定向輸出或報錯
        // http://stackoverflow.com/questions/5255086/when-do-we-need-to-set-useshellexecute-to-true
        p.StartInfo.UseShellExecute = false;
        // ffmpeg 比較特殊,全部信息都從Error出
        p.StartInfo.RedirectStandardError = true;
        //p.StartInfo.RedirectStandardOutput = true;
        p.Start();
        using (var reader = p.StandardError)
        {
            while (!reader.EndOfStream)
                Console.WriteLine(reader.ReadLine());
        }
        // 等待進程
        p.WaitForExit();
    }
}

python

  1. python中可使用fabric這個強大的工具,官方實現是使用python2,不過可以使用pip install fabric3下載它的python3實現。(python3 下使用pip install fabric 也會正常下載,不過沒法使用)
  2. fabric 基礎使用:
    1. fabric中一個函數對應一個任務
    2. 文件名默認命名爲fabfile,否者要使用-f file加載
    3. 使用 fab fun_name

fabfile.py:python

from fabric.api import local
import json

def flv():
    """ 獲取視頻長度 """
    data = local('ffprobe -v quiet -print_format json -show_format -show_streams {0}'.format('1.flv'), capture=True)
    info = json.loads(data.stdout)
    print(info['format']['duration'])

fab flvlinux

bat

  1. 批處理能夠在win中快速編寫簡單命令腳本shell

    REM @echo off
     REM 批量切割視頻
     for %%c in (*.mp4) do (    
         ffmpeg -i %%c -ss 1 -t 1 -v quiet -y %%~nc.flv
         )

powershell

  1. powershell是win上類bash的shell程序,它提供了比批處理更強大的能力,而且如今已開源,微軟也提供了官方的跨平臺實現
  2. 第一次執行xx.ps1腳本,可能會報權限錯誤,在管理員權限的powershell中執行set-ExecutionPolicy RemoteSigned便可,參照張善友大神的博文
  3. powershell的功能很是強大,同時也具備面向對象思惟json

    # 獲取當前目錄全部flv時長
     function FlvInfo ($video)
     {
         $pattern = ".*?(?<Size>\d+).*?"
         $line = ffprobe -v quiet -print_format json -show_format  $video | Where-Object {$_ -like '*size*'}
         $result = $line -match $pattern
         $size = $Matches.Size
         Write-Output "$video size: $size"
     }
    
     foreach ($item in Get-ChildItem -Filter "*.flv*") {
         FlvInfo $item.Name
     }

shell

  1. shell 是linux下的神兵利器,得益於WSL,咱們在Win10下也能自由的使用Shell來完成平常操做c#

    #!/bin/bash
     for video in `ls |grep mp4` 
     do
         ffmpeg -i $video -c:v copy -c:a copy -y ${video:0:-4}.flv
     done

總結

使用c#,python等方式調用命令行程序能夠簡化批量處理大量重複、複雜和流程化的操做,而批處理,powershell,shell也能夠快速簡單地減小命令使用,總的來講要根據具體場景選擇襲擊喜歡的方式吧。api

相關文章
相關標籤/搜索