3

这是我的程序:

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

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

4

5 回答 5

14

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

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)
于 2012-12-24T03:51:17.393 回答
3

您可以处理异常:

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

In [7]: program(argv)
value error handled
于 2012-12-24T03:43:56.167 回答
2

试试这个:

script = argv[0]
try:
    arg1 = argv[1]
except:
    arg1 = ''
于 2012-12-24T04:30:49.507 回答
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"
于 2012-12-24T03:43:15.417 回答
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."
于 2012-12-24T03:57:57.180 回答