.PY
Windows 7のシステム環境変数にファイルを追加しました。変数PATHEXT
にも追加C:\scripts
しましたPATH
。
非常に単純な Python ファイル C:\Scripts\helloscript.py があるとします。
print "hello"
これで、次を使用してコンソールから Python スクリプトを呼び出すことができます。
C:\>helloscript
出力は次のとおりです。
hello
スクリプトをより動的なものに変更する場合は、コンソールの 2 番目のパラメーターとして名前を取得し、それを挨拶と共に出力します。
import sys
print "hello,", sys.argv[1]
出力は次のとおりです。
c:\>helloscript brian
Traceback (most recent call last):
File "C:\Scripts\helloscript.py", line 2, in <module>
print sys.argv[1]
IndexError: list index out of range
sys.argv
次のようになります。
['C:\\Scripts\\helloscript.py']
通常の方法でスクリプトを明示的に呼び出すと、次のようになります。
C:\>python C:\Scripts\helloscript.py brian
出力は次のとおりです。
hello, brian
エラーを回避することはできますが、使用しようとするoptparse
と結果は似ています。
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", "--firstname", action="store", type="string", dest="firstname")
(options, args) = parser.parse_args()
print "hello,", options.firstname
出力は次のとおりです。
hello, None
繰り返しますが、スクリプトを明示的に呼び出すと、スクリプトは正常に機能します。
これが質問です。どうしたの?sys.argv
スクリプトを暗黙的に呼び出すときに、スクリプト名以外の情報が入力されないのはなぜですか?