1

次の「parser.add_option」ステートメントは機能しますが、スクリプトがオプション/引数なしで実行された場合、問題は発生しません。オプション/引数が指定されていない場合、デフォルトでヘルプ (-h / --help) を表示したいと思います。

usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option('-d', '--directory',
        action='store', dest='directory',
        default=None, help='specify directory')
parser.add_option('-f', '--file',
        action='store', dest='filename',
        default=None, help='specify file')
parser.add_option('-v', '--version',
                  action="store_true", dest="show_version",
                  default=False, help='displays the version number')
(options, args) = parser.parse_args()
#if len(args) < 1:
#    parser.error("incorrect number of arguments")

次に、次のスニップを有効にすると、オプション/引数を指定しても「エラー: 引数の数が正しくありません」というメッセージが表示されます。

if len(args) < 1:
parser.error("incorrect number of arguments")

ありがとう。


以下のトレースバック エラーで更新されたコード

def main():
    usage = "usage: %prog [options] arg"
    parser = OptionParser(usage)
    parser.add_option('-d', '--directory',
            action='store', dest='directory',
            default=None, help='specify directory')
    parser.add_option('-f', '--file',
            action='store', dest='filename',
            default=None, help='specify file')
    parser.add_option('-v', '--version',
                      action="store_true", dest="show_version",
                      default=False, help='displays the version number')
    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit()
    (options, args) = parser.parse_args()

#if options.show_version:
#    prog = os.path.basename(sys.argv[0])
#    version_str = "1.0"
#    print "version is: %s %s" % (prog, version_str)
#    sys.exit(0)

filenames_or_wildcards = []

# remove next line if you do not want allow to run the script without the -f -d
# option, but with arguments
filenames_or_wildcards = args # take all filenames passed in the command line

# if -f was specified add them (in current working directory)
if options.filename is not None:
    filenames_or_wildcards.append(options.filename)

トレースバック

$ python boto-backup.py Traceback (most recent call last):   File "boto-backup.py", line 41, in <module>
    filenames_or_wildcards = args # take all filenames passed in the command line NameError: name 'args' is not defined
4

1 に答える 1

1

私はこのようなことをします:

from optparse import OptionParser
import sys

def main():
    usage = "usage: %prog [options] arg"
    parser = OptionParser(usage)
    parser.add_option('-d', '--directory',
            action='store', dest='directory',
            default=None, help='specify directory')
    parser.add_option('-f', '--file',
            action='store', dest='filename',
            default=None, help='specify file')
    parser.add_option('-v', '--version',
                      action="store_true", dest="show_version",
                      default=False, help='displays the version number')
    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit()
    (options, args) = parser.parse_args()
    # rest of program...

if __name__ == '__main__':
    main()

そのため、パーサーとオプションを設定してから、コマンドライン入力があったかどうかを確認します。
何もない場合は、ヘルプ メッセージを出力して終了します。それ以外の場合は、プログラムの実行を続行します。

コマンドライン引数なしで実行すると、出力は次のようになります。

使用法: your_script_name_here.py [オプション] arg

オプション:
  -h, --help このヘルプ メッセージを表示して終了します
  -d ディレクトリ、 --directory=ディレクトリ
                        ディレクトリを指定
  -f ファイル名、--file=ファイル名
                        ファイルを指定
  -v, --version はバージョン番号を表示します

編集 (更新されたコードに応じて):
Python では空白/インデントが重要です。
コードの残りの部分が関数に属するようにインデントされていることを確認してくださいmain()
これ以降filenames_or_wildcards = []、コードはmain()関数のスコープ外にあるため、 という名前の変数がありませんargs

于 2011-03-19T01:46:47.910 に答える