如果未提供命令行参数,则检测并打印

时间:2012-12-24 03:31:33

标签: python

这是我的程序:

from sys import argv

script, arg1 = argv

def program(usr_input, arg1):
    if(usr_input == arg1):
        print "CLI argument and user input are identical"

    else:
        print "CLI argument and user input aren't identical"

if arg1 != "":
    usr_input = raw_input("enter something: ")
    program(usr_input, arg1)

else:
    print "You have not entered a CLI argument at all."

我明白了:

Traceback (most recent call last):
  File "filename.py", line 3, in <module>
    script, arg1 = argv
ValueError: need more than 1 value to unpack

如何检测缺少命令行参数并抛出错误/异常而不是接收此错误?

5 个答案:

答案 0 :(得分:11)

我建议您只检查脚本__main__位置的程序args,作为整个应用程序的入口点。

import sys
import os

def program(*args):
    # do whatever
    pass

if __name__ == "__main__":
    try:
        arg1 = sys.argv[1]
    except IndexError:
        print "Usage: " + os.path.basename(__file__) + " <arg1>"
        sys.exit(1)

    # start the program
    program(arg1)

答案 1 :(得分:3)

您可以处理异常:

In [6]: def program(argv):
    try:
        script, argv1 = argv
    except ValueError:
        print("value error handled")
   ...:         

In [7]: program(argv)
value error handled

答案 2 :(得分:2)

试试这个:

script = argv[0]
try:
    arg1 = argv[1]
except:
    arg1 = ''

答案 3 :(得分:1)

您可以在那里使用try语句:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import sys

class MyError(Exception):
    def __init__(self, value):
        self.error_string = value

    def __str__(self):
        return eval(repr(self.error_string))

try:
    script, arg1 = sys.argv

except ValueError:     
    raise MyError, "Not enough arguments"

答案 4 :(得分:1)

看到sys.argv是一个列表,你应该检查列表的长度,以确保它是你想要的。您的脚本稍作修改以检查长度:

from sys import argv

def program(usr_input, arg1):
    if(usr_input == arg1):
        print "CLI argument and user input are identical"
    else:
        print "CLI argument and user input aren't identical"

if len(argv)== 2:
    arg1 = argv[1]
    usr_input = raw_input("enter something: ")
    program(usr_input, arg1)
else:
    print "You have not entered a CLI argument at all."