LoginSignup
3
4

More than 3 years have passed since last update.

PowershellからPythonの関数を実行(引数の渡し方)

Last updated at Posted at 2020-01-21

やりたいこと

PowershellからPythonの関数を実行したい

ポイント

  • 引数はコマンドライン引数を使用すること
  • sys.argvは文字列なので数値を渡したい時はcastが必要
import sys
#引数をsys.argv[n]を使用して定義する
a = sys.argv[1]

サンプルコード

calc.py
def add(a, b):                   
    return a + b
main.py
from calc import add
import sys

a = int(sys.argv[1])
b = int(sys.argv[2])

ret = add(a, b)
print(ret)
test.ps
$a = 5
$b = 10
python.exe main.py $a $b
結果
6

つまづいたところ

・引数を渡す時にPowershellの関数に渡すようなやり方をしたため
 引数の定義エラーになった

calc.py
def add(a, b):                   
    return a + b
main.py
from calc import add
ret = add(a, b)
print(ret)
test.ps
$a = 5
$b = 10
python.exe main.py $a $b
結果
NameError: name 'a' is not defined
3
4
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
3
4