强制参数成为有效路径
Forcing an argument to be a valid path
我正在编写一个简单的脚本,用于解析存储在 AWS CloudWatch 上的 JSON 文件的内容。我在脚本中添加了一个参数解析器,它将接受用户输入,并允许用户将文件的输出打印到屏幕上(以预定方式),或者允许他们将内容输出到本地 JSON 文件。这是困扰我的片段:
import argparse
parser = argparse.ArgumentParser(description="Process a log file")
parser.add_argument('-o', '--output', choices=[???, 'print'],
default='print', help='Specify logfile output path or print to screen')
args = parser.parse_args()
我的问题源于 parser.add_argument
行,特别是 choices
论点。我想为这个标志允许两个输入,那些是 print
或者他们本地机器上的一些有效路径。我希望当前用问号标记的选项是 Python 可以识别的路径。
有没有办法使用 argparse 指定标志的参数之一必须是 PATH?到目前为止,搜索结果尚无定论。
提前致谢!
使用 type
keyword argument 到 add_argument
,而不是 choices
。正如文档所说:
The type keyword argument of add_argument()
allows any necessary
type-checking and type conversions to be performed.
def myfiletype(arg):
if arg == 'print' or os.path.isdir(arg):
return arg
else:
raise ValueError('Invalid path specification')
parser.add_argument('-o', '--output', type=myfiletype,
default='print',
help='Specify logfile output path or print to screen')
定义自定义 type
(如 ),其中值可以是有效路径或 'print'
。 choices
不是正确的选择。
我正在编写一个简单的脚本,用于解析存储在 AWS CloudWatch 上的 JSON 文件的内容。我在脚本中添加了一个参数解析器,它将接受用户输入,并允许用户将文件的输出打印到屏幕上(以预定方式),或者允许他们将内容输出到本地 JSON 文件。这是困扰我的片段:
import argparse
parser = argparse.ArgumentParser(description="Process a log file")
parser.add_argument('-o', '--output', choices=[???, 'print'],
default='print', help='Specify logfile output path or print to screen')
args = parser.parse_args()
我的问题源于 parser.add_argument
行,特别是 choices
论点。我想为这个标志允许两个输入,那些是 print
或者他们本地机器上的一些有效路径。我希望当前用问号标记的选项是 Python 可以识别的路径。
有没有办法使用 argparse 指定标志的参数之一必须是 PATH?到目前为止,搜索结果尚无定论。
提前致谢!
使用 type
keyword argument 到 add_argument
,而不是 choices
。正如文档所说:
The type keyword argument of
add_argument()
allows any necessary type-checking and type conversions to be performed.
def myfiletype(arg):
if arg == 'print' or os.path.isdir(arg):
return arg
else:
raise ValueError('Invalid path specification')
parser.add_argument('-o', '--output', type=myfiletype,
default='print',
help='Specify logfile output path or print to screen')
定义自定义 type
(如 ),其中值可以是有效路径或 'print'
。 choices
不是正确的选择。