0
0

PythonスクリプトからPowerShellスクリプトを実行したときPauseコマンドをスキップして停止しないようにする

Last updated at Posted at 2024-06-19

前提

以下の記事の続きです。

PythonスクリプトからPowerShellを実行した際、PowerShellスクリプトにあるpauseコマンドレットで処理が止まってしまう。処理を止めたくないのならpauseを削除すればよいのだがPythonスクリプトからではなくPowerShellスクリプトを直接実行する場合はpauseで止まってほしい。Pythonスクリプトから実行した場合のみpauseをスキップできないか考えた。

PowerShellの処理

pauseコマンドレットを3つ用意する。3回文字入力をすると処理が終了する。

pause
pause
pause

Pythonの処理

2通りの処理を用意する。pauseコマンドレットをスキップできるのは(2)の場合。
(1)単にpowershellコマンドを実行する
(2)echoコマンドをパイプラインでpowershellコマンドに渡す
 エコーコマンドで指定する文字列は任意

b.py
import subprocess

ps_file = 'C:\\PyWork\\a.ps1'

print('(1)')
ps_cmd = 'powershell -ExecutionPolicy RemoteSigned -File'
cmd = subprocess.run(ps_cmd + ' ' + ps_file)

print('(2)')
ps_cmd = 'powershell -Command echo "PYTHON" | powershell -ExecutionPolicy RemoteSigned -File'
cmd = subprocess.run(ps_cmd + ' ' + ps_file)

print('(3)')
ps_cmd = 'powershell -Command Write-Host y | powershell -ExecutionPolicy RemoteSigned -File'
cmd = subprocess.run(ps_cmd + ' ' + ps_file)

実行結果

(1)エンターキーを3回押さないと処理が完了しない
(2)エンターキーを押さなくても自動で処理が完了する

C:\PyWork> python b.py
(1)
続行するには、Enter キーを押してください...: 
続行するには、Enter キーを押してください...: 
続行するには、Enter キーを押してください...: 
(2)
続行するには、Enter キーを押してください...: PYTHON
続行するには、Enter キーを押してください...:
続行するには、Enter キーを押してください...:
(3)
y
続行するには、Enter キーを押してください...: 
続行するには、Enter キーを押してください...:
続行するには、Enter キーを押してください...:
0
0
1

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