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スクリプトからPowerShellスクリプトを実行する

Last updated at Posted at 2024-06-15

前提

  • ユーザは Python スクリプトを実行する
  • Python は PowerShell に引数を渡して処理を実行する
  • PowerShell は Python に結果を返却する

環境

Python 3.12.4

Pythonの処理

a.py
import subprocess
import random

ps_cmd = 'powershell -ExecutionPolicy RemoteSigned -File'
ps_file = 'C:\\PyWork\\IsEvenNumber.ps1'

# 0~9の整数を生成
num = random.randint(0, 9)

# PowerShellのスクリプトを実行して偶数か否か判定する
cmd = subprocess.run(ps_cmd + ' ' + ps_file + ' ' + str(num))

if cmd.returncode == 1:
	# 偶数の場合
	print(str(num) + " is Even")
else:
	# 奇数の場合
	print(str(num) + " is Odd")

PowerShellの処理

IsEvenNumber.ps1
# 受け取った引数は $Args[0] に格納される
$num = $Args[0]

if ($num % 2 -eq 0) {
    # 偶数なら 1 を返却
	$result = 1
} else {
    # 奇数なら 0 を返却
	$result = 0
}

# exit 値を返却する
exit $result

実行結果

C:\PyWork> python a.py
4 is Even

参考資料

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?