Pythonのsubprocessモジュールの使い方は?

subprocessモジュールはPythonにおいて子プロセスを作成し管理するためのモジュールです。外部のコマンドを実行し、それとやり取りする簡単な方法を提供します。以下にsubprocessモジュールのいくつかの一般的なメソッドと使用例を示します。

  1. run()関数は、外部コマンドを実行し、コマンドの完了を待機するために使用されます。実行結果を含むCompletedProcessオブジェクトが返されます。
import subprocess

result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout)
  1. Popen()関数:この関数は、子プロセスのオブジェクトを作成し、その子プロセスを実行、制御、および対話するために使用されます。
import subprocess

process = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
output, error = process.communicate()
print(output)
  1. check_output()関数は、外部コマンドを実行し、その出力結果を返すためのものです。コマンドの実行が失敗した場合はCalledProcessError例外が発生します。
import subprocess

output = subprocess.check_output(['ls', '-l'], text=True)
print(output)
  1. 「communicate()メソッド:このメソッドは、子プロセスとのやり取りに使用されます。子プロセスに入力データを送信し、子プロセスからの出力結果やエラーメッセージを取得します。」
import subprocess

process = subprocess.Popen(['grep', 'hello'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
output, error = process.communicate(input='hello world')
print(output)

以上はsubprocessモジュールの一部の一般的なメソッドと使用例です。具体的なニーズに応じて、適切な方法を選択してサブプロセスを実行および管理できます。

bannerAds