还有其他方法可以验证python3中的命令行参数吗?

在没有外部模块和argparse的情况下,还有其他更有效的方法来验证命令行args吗?

import sys
import getopt

argv = sys.argv[1:]
try:
    opts,args = getopt.getopt(argv,"h",["help","version","number="])
except getopt.GetoptError as error:
    print(error)
    exit(1)
if args:
    exit(1)
print(opts)
print(args)

所以这是我要怎么做,但是可以吗?我是python的新手,并尝试使用尽可能多的python功能

linlaiku 回答:还有其他方法可以验证python3中的命令行参数吗?

您应该查看Python的内置argparse。从命令行手动解析复杂的命令会花费很多麻烦。您可以强制某些参数为某种类型或值。

用法示例:

import sys
import argparse

PHASES = ['clean','package','install','test','deploy']
ALT_PHASES = ['docs','demos','update']

parser = argparse.ArgumentParser()
parser.add_argument(
    'phase',help="the target phase",choices=PHASES + ALT_PHASES
)
parser.add_argument(
    '--skip-demos',help="skip packaging and deployment of demos",action='store_const',const=str
)
parser.add_argument(
    '--skip-docs',help="skip generation and deployment of user's guide",const=str
)
parser.add_argument(
    '--skip-tests',help="skip tests",const=str
)
parser.add_argument(
    '--skip-wheels',help="skip wheel generation",action="store_const",const=str
)
parser.add_argument(
    '--update',help="update the source code in the virtual environment; do not make the wheels",const=str
)

def main(args):
    parsed_args = parser.parse_args(args)
    print(parsed_args.phase) # prints the phase


if __name__ == "__main__":
    main(sys.argv[1:])

输入无效参数时的示例输出:

$ python3 build.py hello
usage: build.py [-h] [--skip-demos] [--skip-docs] [--skip-tests]
                [--skip-wheels] [--docs-branch DOCS_BRANCH]
                [--skip-formatting] [--int-tests] [--update]
                {clean,package,install,test,deploy,docs,demos,update}
build.py: error: argument phase: invalid choice: 'hello' (choose from 'clean','deploy','docs','update')
,

Python中有几个不错的库来支持命令行解析和参数验证。

我过去曾经尝试过Argparse,但效果很好。您可以参考this的答案以了解如何使用Argparse。

希望有帮助!

本文链接:https://www.f2er.com/3121270.html

大家都在问