Python argparse:使用

2024-03-28 20:08:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用argparse使用以下helper函数解析参数:

def get_cli_arguments():
    parser = argparse.ArgumentParser(prog='Xtrayce')
    parser.add_argument(
        "-o", "--output",
        default=get_default_output_path(),
        help="Supply an output path.",
        type=argparse.FileType('wb'),
    )
    parser.add_argument(
        "-d", "--dry",
        help="Don't save a file with the output.",
        action="store_true",
    )
    parser.add_argument(
        "-s", "--standard",
        help="Also scan standard library and modules.",
        action="store_true",
    )

我希望每当用户指定--dry标志时,都不会从--output参数创建任何文件。你知道吗

当用户指定--dry,同时仍然使用default=type=argparse.FileType("wb")时,“取消”文件创建的最佳方式是什么?你知道吗


Tags: pathadddefaultparseroutput参数gettype
1条回答
网友
1楼 · 发布于 2024-03-28 20:08:45

没有简单的方法可以通过默认的ArgumentParser实现这一点,因为在解析参数的过程中已经创建了文件。你知道吗

您可以将 output的类型更改为字符串,并在写入之前添加检查:

parser = argparse.ArgumentParser(prog='Xtrayce')
parser.add_argument(
    "-o", " output",
    default=get_default_output_path(),
    help="Supply an output path.",
)
parser.add_argument(
    "-d", " dry",
    help="Don't save a file with the output.",
    action="store_true",
)

if not args.dry:
    with open(args.output, 'wb') as f:
        f.write(...)

或者不使用 dry参数,您可以提供-作为 output参数,它将写入sys.stdout而不是文件。你知道吗

the docs

FileType objects understand the pseudo-argument '-' and automatically convert this into sys.stdin for readable FileType objects and sys.stdout for writable FileType objects:

parser.add_argument('infile', type=argparse.FileType('r'))
parser.parse_args(['-']) Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)```

相关问题 更多 >