检查python中的命令行参数的数量

mdm*_*ard 6 python command-line-arguments

我是python的新手.仍然让我的脚湿透.我正在尝试做这样的事情:

import sys

if ((len(sys.argv) < 3 or < len(sys.argv > 3)):
    print """\
This script will compare two files for something
and print out matches

Usage:  theScript firstfile secondfile
"""
    return
Run Code Online (Sandbox Code Playgroud)

我想在脚本的开头执行此操作以检查正确数量的参数.问题是"返回"在这里不起作用.如果我想的话,我可以做一些大事,但我希望不必这样做.不确定是否有更简单的方法.有任何想法吗?

gar*_*epy 6

使用sys.exit()从脚本退出.

import sys

if ((len(sys.argv) < 3 or  len(sys.argv > 3)):  ## also removed extra `<`
    print """\
This script will compare two files for something
and print out matches

Usage:  theScript firstfile secondfile
"""
    sys.exit(0)
Run Code Online (Sandbox Code Playgroud)

  • 程序正在退出,因为出现了错误; 你应该使用`sys.exit(1)`. (3认同)