簡體   English   中英

用命令行中的另一個參數覆蓋位置和可選參數(argparse python模塊)

[英]Override the positional and optional arguments with another argument in command line (argparse python module)

我正在使用argparser來解析命令行參數。

現在,我有類似的東西

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

這里前兩個是位置參數,其余是可選的。

現在,我希望有一個功能,當用戶在命令行中輸入文件名作為輸入時,它應覆蓋上述參數並從文件頭獲取參數。 我覺得當用戶給出類似的東西時

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

在命令行中給出這個:

./script.py -f filename 

它不應該抱怨上述位置論點。

這比我目前的實施更可行嗎?

您很可能需要自己實施此檢查。 使兩個參數(位置和-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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM