Hut*_*tch 1 python argparse python-3.x
我有一个 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()
Run Code Online (Sandbox Code Playgroud)
目前,当我运行python test.py arg1 arg2时,错误是
error: unrecognized arguments: arg1 arg2
Run Code Online (Sandbox Code Playgroud)
我希望代码允许用户在需要查看说明时使用 -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()
Run Code Online (Sandbox Code Playgroud)
小智 7
尝试以下代码:-
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()
Run Code Online (Sandbox Code Playgroud)
所有未知的参数都将在 中进行解析unknown并在 中全部已知args。