簡體   English   中英

使用argparse允許未知參數

[英]Allow unknown arguments using argparse

我有一個python腳本,要求用戶輸入兩個參數來運行它,這些參數可以命名為任何東西。

我還使用了argparse,以允許用戶使用開關'-h'來獲取運行腳本所需的指令。

問題是,現在我使用argparse時,在腳本中傳遞兩個隨機命名的參數時出現錯誤。

import argparse

parser = argparse.ArgumentParser(add_help=False)

parser.add_argument('-h', '--help', action='help',
                    help='To run this script please provide two arguments')
parser.parse_args()

當前當我運行python test.py arg1 arg2時 ,錯誤是

error: unrecognized arguments: arg1 arg2

我希望該代碼允許用戶使用-h運行test.py(如果需要查看說明),但也允許他們使用任意兩個參數運行腳本。

帶有幫助標簽的分辨率 ,可為用戶提供有關所需參數的上下文。

   parser = argparse.ArgumentParser(add_help=False)

    parser.add_argument('-h', '--help', action='help', help='To run this script please provide two arguments: first argument should be your scorm package name, second argument should be your html file name. Note: Any current zipped folder in the run directory with the same scorm package name will be overwritten.')
    parser.add_argument('package_name', action="store",  help='Please provide your scorm package name as the first argument')
    parser.add_argument('html_file_name', action="store", help='Please provide your html file name as the second argument')

    parser.parse_args()
import argparse

parser = argparse.ArgumentParser(description='sample')

# Add mandatory arguments
parser.add_argument('arg1', action="store")
parser.add_argument('arg2', action="store")

# Parse the arguments
args = parser.parse_args()
# sample usage of args
print (float(args.arg1) + float(args.arg2))

您需要將這些參數添加到解析器中:

parser.add_argument("--arg1", "-a1", dest='arg1', type=str)
parser.add_argument("--arg2","-a2", dest='arg2', type=str)

如果這些參數沒有參數required = true ,則可以在沒有此參數的情況下調用該程序,因此可以僅使用-h標志運行該程序。 要使用參數運行程序:

python test.py --arg1 "Argument" --arg2 "Argument"

然后,要在變量中包含參數,您必須閱讀它們:

args = parser.parse_args()
argument1=args.arg1
argument2=args.arg2

嘗試以下代碼:-

 import argparse

 parser = argparse.ArgumentParser(add_help=False)

 parser.add_argument('-h', '--help', action='help',
                help='To run this script please provide two arguments')
 parser.add_argument('arg1')
 parser.add_argument('arg2')

 args, unknown = parser.parse_known_args()

您所有未知的參數將在unknown解析,而所有args均在args解析。

暫無
暫無

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

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