1

コマンドライン引数を解析するために argparser を使用しています。

今、私は次のようなものを持っています

./script.py 1112323 0 --salary 100000 -- age 34

ここで、最初の 2 つは位置引数で、残りはオプションです。

ここで、ユーザーがコマンドラインで入力としてファイル名を指定すると、これらの上記の引数をオーバーライドして、ファイルのヘッダーから引数を取得する機能が必要です。ユーザーが sth like を与えると、私は意味します

id|sequence|age|name|...........   (header of the file with first two cols as positional arguments and rest positional)

これをコマンドラインで指定すると:

./script.py -f filename 

上記の位置引数について不平を言うべきではありません。

これは私の現在の実装で実行可能ですか?

4

1 に答える 1

3

ほとんどの場合、このチェックを自分で実装する必要があります。両方の引数 (positional および -f) をオプション (required=False および nargs="*") にしてから、カスタム チェックを実装し、ArgumentParser のエラー メソッドを使用します。ユーザーがヘルプ文字列で正しい使用方法を簡単に説明できるようにします。

このようなもの:

parser = ArgumentParser()
parser.add_argument("positional", nargs="*", help="If you don't provide positional arguments you need use -f")
parser.add_argument("-f", "--file", required=False, help="...")
args = parser.parse_args()

if not args.file and not args.positional:
    parser.error('You must use either -f or positional argument')
于 2013-05-13T07:52:59.333 に答える