簡體   English   中英

在 python3 中是否有其他驗證命令行參數的方法?

[英]Are there other ways of validating command line args in python3?

是否有其他更有效的方法來驗證沒有外部模塊和 argparse 的命令行參數?

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 功能

您應該查看 Python 的內置argparse 從命令行手動解析復雜的命令會省去很多麻煩。 您可以強制某些 arguments 為某個類型或值。

示例用法:

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",
    action='store_const',
    const=str
)
parser.add_argument(
    '--skip-tests',
    help="skip tests",
    action='store_const',
    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",
    action="store_const",
    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:])

輸入無效參數時的示例 output:

$ 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', 'package', 'install', 'test', 'deploy', 'docs', 'demos', 'update')

Python 中有幾個很好的庫來支持命令行解析和參數驗證。

我過去曾嘗試過Argparse ,效果很好。 您可以參考答案以了解如何使用 Argparse。

希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM