\

Pythonのsubprocessモジュールを使用すると、シェルコマンドを実行できます。しかし、コマンドライン引数にダブルクォートが含まれている場合、適切に扱う方法が必要です。

ダブルクォートを含むコマンドの実行

ダブルクォートを含むコマンドを実行する場合、subprocess.Popen()subprocess.check_output()などの関数を使用します。しかし、ダブルクォートを含む文字列をそのまま渡すと、エラーが発生することがあります。

例えば、次のようなffmpegのコマンドを実行したいとします。

ffmpeg -i "concat:1.ts|2.ts" -vcodec copy -acodec copy temp.mp4

このコマンドをsubprocess.Popen()に渡すとき、ダブルクォートを含む文字列をそのまま渡すと、ffmpegはエラーを返します。

ダブルクォートを含むコマンドの正しい渡し方

ダブルクォートを含むコマンドを正しく渡すためには、次の2つの方法があります。

  1. コマンドを文字列ではなく、リストとして渡す。
  2. shell=Trueを指定して、文字列をシェルに解釈させる。

リストとしてコマンドを渡す

コマンドをリストとして渡すと、各引数が個別に扱われ、シェルのクオーティングを気にする必要がありません。

command = ["ffmpeg", "-i", "concat:1.ts|2.ts", "-vcodec", "copy", "-acodec", "copy", "temp.mp4"]
output, error = subprocess.Popen(command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

shell=Trueを指定する

shell=Trueを指定すると、コマンドを文字列として渡すことができます。この場合、シェルがコマンドを解釈するため、ダブルクォートを適切に扱うことができます。

command = 'ffmpeg -i "concat:1.ts|2.ts" -vcodec copy -acodec copy temp.mp4'
output, error = subprocess.Popen(command, universal_newlines=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

これらの方法を使用すると、Pythonのsubprocessモジュールでダブルクォートを含むコマンドを正しく扱うことができます。適切な方法を選択して、コマンドを実行しましょう。

投稿者 admin

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です