Open6
【Python】subprocess実行例
引数をつけてtest.batを実行
sample code
import subprocess
# バッチファイルに引数を渡して実行
subprocess.run(["test.bat", "hello", "world"])
実行例
python .\main.py
arg1: hello
arg2: world
arg3:
arg4:
arg5:
arg6:
続行するには何かキーを押してください . . .
test.bat の中身(実行時の引数を標準出力する)
@echo off
echo arg1: %1
echo arg2: %2
echo arg3: %3
echo arg4: %4
echo arg5: %5
echo arg6: %6
pause
引数に数字を付けて実行
import subprocess
# バッチファイルに引数を渡して実行
subprocess.run(["test.bat", "hello", "world", "123"])
# 例1: 引数に別の数字を追加
subprocess.run(["test.bat", "hello", "world", "456"])
# 例2: 引数に複数の数字を追加
subprocess.run(["test.bat", "foo", "bar", "789", "1011"])
# 例3: 数字のみを引数に渡す
subprocess.run(["test.bat", "100", "200", "300"])
python .\main.py
arg1: hello
arg2: world
arg3: 123
arg4:
arg5:
arg6:
続行するには何かキーを押してください . . .
arg1: hello
arg2: world
arg3: 456
arg4:
arg5:
arg6:
続行するには何かキーを押してください . . .
arg1: foo
arg2: bar
arg3: 789
arg4: 1011
arg5:
arg6:
続行するには何かキーを押してください . . .
arg1: 100
arg2: 200
arg3: 300
arg4:
arg5:
arg6:
続行するには何かキーを押してください . . .
応用編
引数に可変値を利用する
sample code
import subprocess
import os
counter_file = "counter.txt"
# counter.txt からカウント値を取得し、なければ1に初期化
if os.path.exists(counter_file):
with open(counter_file, "r") as f:
try:
count = int(f.read().strip())
except ValueError:
count = 1
else:
count = 1
# バッチファイルに引数を渡して実行
subprocess.run(["test.bat", "hello", "world", str(count), "123"])
# カウント値をインクリメントして保存
with open(counter_file, "w") as f:
f.write(str(count + 1))
# test.bat の内容は以下の通り
# @echo off
# echo %1 %2 %3 %4
# pause
# このスクリプトは、test.bat を呼び出し、引数として "hello", "world", 現在のカウント値, "123" を渡します。
# 実行後、カウント値を1増やして counter.txt に保存します。
# 注意: このコードは Windows 環境での実行を想定しています。
実行例 引数の値が1,2,3と増えている
PS> python .\main.py
hello world 1 123
続行するには何かキーを押してください . . .
PS>
PS> python .\main.py
hello world 2 123
続行するには何かキーを押してください . . .
PS>
PS> python .\main.py
hello world 3 123
続行するには何かキーを押してください . . .
PS>
PS>
応用編2
・test.txtに書かれている内容を引数にする。
(1回目はtest.txtの1行目、2回目はtest.txtの2行目の内容を引数にする。)
import subprocess
import os
counter_file = "counter.txt"
test_file = "test.txt"
# test.txt の内容を行ごとに取得
with open(test_file, "r", encoding="utf-8") as f:
lines = [line.strip() for line in f if line.strip()]
# counter.txt からカウント値を取得し、なければ1に初期化
if os.path.exists(counter_file):
with open(counter_file, "r") as f:
try:
count = int(f.read().strip())
except ValueError:
count = 1
else:
count = 1
# 行番号は1始まりなので、インデックスは count-1
if 1 <= count <= len(lines):
args = lines[count - 1].split()
else:
args = []
if args:
subprocess.run(["test.bat"] + args)
# カウント値をインクリメントして保存
with open(counter_file, "w") as f:
f.write(str(count + 1))
# test.bat の内容は以下の通り
# @echo off
# echo %1 %2 %3 %4
# pause
# このスクリプトは、test.bat を呼び出し、引数として "hello", "world", 現在のカウント値, "123" を渡します。
# 実行後、カウント値を1増やして counter.txt に保存します。
# 注意: このコードは Windows 環境での実行を想定しています。
test.txt の内容
日本 関東 東京
赤 黄 青
春 夏 秋 冬
2025 01/01 10:10:10
実行例
PS> python .\main.py
日本 関東 東京
続行するには何かキーを押してください . . .
PS> python .\main.py
赤 黄 青
続行するには何かキーを押してください . . .
PS> python .\main.py
春 夏 秋 冬
続行するには何かキーを押してください . . .
PS> python .\main.py
2025 01/01 10:10:10
続行するには何かキーを押してください . . .
ブラウザを起動する(Chrome ,Edge)
import subprocess
# Chromeを起動
subprocess.run(["start", "chrome"], shell=True)
# Edgeを起動
subprocess.run(["start", "msedge"], shell=True)
補足 (Bat, Powershellでブラウザを起動する方法は以下で紹介)
・Bat ver ・Ps ver
subprocess return code の確認例
・ブラウザなどは起動すれば簡単に成功したとわかるが、中にはreturn code を確認しないとわからないものもある。
return code が 0 なら成功と表示
import subprocess
# Chromeを起動
result = subprocess.run(["start", "chrome"], shell=True, capture_output=True, text=True)
if result.returncode == 0:
print("Chrome起動成功")
else:
print("Chrome起動失敗:", result.stderr)
# Edgeを起動
result = subprocess.run(["start", "msedge"], shell=True, capture_output=True, text=True)
if result.returncode == 0:
print("Edge起動成功")
else:
print("Edge起動失敗:", result.stderr)
Subprocess実行時の標準エラー出力を確認する。
・今回は存在しないコマンドを実行させてその結果を表示する。
sample code
import subprocess
# 存在しないブラウザを起動(エラー発生例)
result = subprocess.run(["start", "notfoundbrowser"], shell=True, capture_output=True, text=True)
print("標準エラー出力:", result.stderr)
if result.returncode != 0:
print("起動失敗:", result.stderr)
実行結果
PS> python .\main.py
標準エラー出力: ファイル notfoundbrowser が見つかりません。
起動失敗: ファイル notfoundbrowser が見つかりません。
PS>