Argparse URL 类型

Juh*_*has 0 python argparse

让我们有一个简单的 argparser,其中一个参数代表 URL。

from argparse import ArgumentParser

def my_url(arg):
"""
Some url validation

"""

parser = ArgumentParser(
    description="foobar"
)
parser.add_argument(
    "-u",
    "--url",
    type=my_url,
    help="foobar",
)
Run Code Online (Sandbox Code Playgroud)

是否准备好接受函数来验证参数是否为 URL,以便省略my_url自定义验证函数?

rda*_*das 5

您可以使用urlparse&urllib.parse检查它是否能够从 URL 中提取所有必需的组件:

from urllib.parse import urlparse


def my_url(arg):
    url = urlparse(arg)
    if all((url.scheme, url.netloc)):  # possibly other sections?
        return arg  # return url in case you need the parsed object
    raise ArgumentTypeError('Invalid URL')
Run Code Online (Sandbox Code Playgroud)

结果:

parser.parse_args(['-u', 'http://locahost:2000'])  # pass
parser.parse_args(['-u', 'http/locahost:2000'])  # Invalid URL
parser.parse_args(['-u', 'thisisurl'])  # Invalid URL
Run Code Online (Sandbox Code Playgroud)