Python > 引数の処理

更新日 2014-10-19
広告
Pythonスクリプトに対する引数を処理するためにはsysパッケージを使います。
import sys

argvs = sys.argv

for arg in argvs:
    print arg
これを実行すると、以下のようになります。
$ python test.py a b 1
test.py
a
b
1
4

実行しているスクリプト名が最初の引数になっていることに注意してください。

C言語のgetoptと同様の機能もあります。 以下にサンプルコードを示します。

import sys
import getopt

opts, args = getopt.getopt(sys.argv[1:], "d:f:")

for opt, arg in opts:
    if opt == "-d":
        print arg
    elif opt == "-f":
        print arg
広告
お問い合わせは sweng.tips@gmail.com まで。
inserted by FC2 system