LoginSignup
1
0

More than 1 year has passed since last update.

Python3.7以降でsubprocess.run()関数を使いexe実行

Last updated at Posted at 2021-10-17

Python3.7以降でexeを実行する

Python3.5以降でexeを実行するには、subprocess.runを使います。
(※Python3.4以前はsubprocess.callです。)
そしてこの記事で紹介するパラーメータは3.7以降のものなのでご注意ください。

コマンドプロンプトで以下コマンドで実行するexeを例に説明します。
(例)cmd> sample.exe /a /b /c

import subprocess

result = subprocess.run("sample.exe /a /b /c")
print(result)
#戻り値
#CompletedProcess(args='sample.exe', returncode=0)

 

戻り値の通り、これだけでは出力結果やエラー出力結果が得られません。
そこで、capture_outputtextパラメータを設定してやります。

import subprocess

result = subprocess.run("sample.exe /a /b /c, capture_output=True, text=true")
print(result)
#戻り値
#これはサンプルです。

capture_output
trueを指定すると、出力結果、出力エラー結果を得られます。
text
trueにすると戻り値を文字列として受け取れるようになり便利です。指定しなければバイトデータとして返ってきます。

さいごに

今回は1分以内に直感的にPythonでexeを実行する方法を伝えたかったため、最小限の説明としました。
これ以外にもsubprocessはたくさんパラメータや使い方が存在するのでぜひ調べてみてください。

参考サイト

Python 3のsubprocess.run()の使い方
subprocess --- サブプロセス管理

1
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
1
0