0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】Shell Scriptを実行する方法(Mac/Linux向け)

0
Posted at

【Python】Shell Scriptを実行する方法(Mac/Linux向け)

PythonからShell Script(例: bashの.shファイル)を実行する方法を紹介します。

✅ サンプルコード

import subprocess

# capture_output=True: 標準出力・標準エラー出力を取得する
# text=True: 出力をバイト列ではなく文字列として扱う
result = subprocess.run(['bash', 'test.sh'], capture_output=True, text=True)
print(result.stdout)

📝 説明

  • subprocess.run() は外部プログラムを実行する関数です。
  • ['bash', 'test.sh'] は bash 経由で test.sh を実行しています。
  • capture_output=True にすると標準出力・エラー出力を Python 側で取得できます。
  • text=True を指定すると、出力をバイトではなく文字列として扱えます。

📌 注意点

  • test.sh に実行権限が必要な場合があります(chmod +x test.sh)。
  • 実行するスクリプトは相対パスまたは絶対パスで指定してください。
  • 同じディレクトリ内にtest.shが存在する場合のコードです

Mac や Linux での自動化処理やCI環境などで便利に使えます!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?