简体   繁体   中英

Detect and print if no command line argument is provided

This is the program I have:

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."

I get:

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

How can I detect the lack of command line argument and throw an error/exception instead of receiving this error?

I would recommend just checking the program args in the __main__ location of your script, as an entry point to the entire application.

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)

You can handle the exception:

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

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

try this:

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

You could use a try statement there:

#!/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"

Seeing that sys.argv is a list you should check the length of the list to make sure it is what you wish it to be. Your script with minor changes to check the length:

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."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM