daalgoo
daalgoo

Reputation: 75

how do I print error when no argv is provided

Please help.

I have a situation where I want to provide an IP address to my script and I want to print an error msg when the address is not provided.

    ip = sys.argv[1]


    if len(ip) == 13:
            print "IP address format correct"
    else:
            print "wrong IP format"
            exit()

I know I will have to work on the length but that is for later...

Upvotes: 2

Views: 563

Answers (4)

Cipher
Cipher

Reputation: 99

Try this, it will check if ip is given as input and also validate it.

import re
import sys

#check if ip is given
if len(sys.argv) == 2:
    # regex checking
    s = re.compile('[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')
    # your input
    ip = sys.argv[1]
    if s.match(ip):
        print("{} is valid".format(ip))
    else :
        print("{} is not valid".format(ip))
else:
    print("input ip address")

Upvotes: 1

ABarrier
ABarrier

Reputation: 952

The following code:

import sys

if __name__ == "__main__":
    # print the given IP to the script
    ip = sys.argv[1]
    print(ip)

    # your condition
    if len(ip) == 13:
        print("IP address format is correct")
    else:
        print("wrong IP format")
        exit()

saved as a script test.py along with calling the script as:

python3 test.py 255.255.255.0

or in Python 2.X

python test.py 255.255.255.0

will do more of less what you want to do for an IP input example as: 255.255.255.0

Upvotes: 1

chepner
chepner

Reputation: 531430

Use argparse and let it handle this for you.

import argparse
import ipaddress


p = argparse.ArgumentParser()
p.add_argument("address", type=ipaddress.ip_address)

args = p.parse_args()  # Without an argument, parse sys.argv[1:]

The ipaddress module will take care of validating the IP address. In Python 2.7, you can install ipaddr instead and use that, with some slight adjustments. (ipaddress is just a slightly modified version of ipaddr included in the standard library starting in Python 3.3.)

Upvotes: 1

Prashant Kumar
Prashant Kumar

Reputation: 2092

You can check if the length of args provided is equal to 2 or not. The first argument is always the filename stored at argv[0]. So you have to check if length is 2 or more.

Try this :

if len(sys.argv) < 2:
    print("Please provide an IP to proceed.")
    sys.exit(0)

ip = sys.argv[1]


if len(ip) == 13:
    print "IP address format correct"
else:
    print "wrong IP format"
    exit()

Upvotes: 3

Related Questions