syed.hamid
syed.hamid

Reputation: 15

Type of the positional parameters in python

I'm quite new to python programming and I come from a Unix/Linux administration and shell scripting background. I'm trying to write a program in python which accepts command line arguments and depending on there type (int, str) performs certain action. However in my case the input is always being treated as string.Please advice.

#!/usr/bin/python
import os,sys,string
os.system('clear')

# function definition
def fun1(a):
           it = type(1)
           st = type('strg')
           if type(a) == it:
                c = a ** 3
                print ("Cube of the give int value %d is %d" % (a,c))
           elif type(a) == st:
                b = a+'.'
                c = b * 3
                print ("Since given input is string %s ,the concatenated output is %s" % (a,c))


a=sys.argv[1]
fun1(a)

Upvotes: 0

Views: 639

Answers (3)

jamylak
jamylak

Reputation: 133534

import argparse, ast

parser = argparse.ArgumentParser(description="Process a single item (int/str)")
parser.add_argument('item', type=ast.literal_eval,
                    help='item may be an int or a string')
item = parser.parse_args().item


if isinstance(item, int):
    c = item ** 3
    print("Cube of the give int value %d is %d" % (item,c))
elif isinstance(item, str):
    b = item + '.'
    c = b * 3
    print("Since given input is string %s ,the concatenated output is %s"
          % (item,c))
else:
    pass # print error

Upvotes: 0

Bhavish Agarwal
Bhavish Agarwal

Reputation: 673

First of all, the input will always be treated as string.

You could use argparse:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("cube", type=int,
                help="Cube of the give int value ")

args = parser.parse_args()
answer = args.cube**3

print answer

python prog.py 4
64

All the integers have an attribute __int__, so you could use that attribute to differentiate between int and string.

if hasattr(intvalue, __int__):
    print "Integer"

Upvotes: 0

l4mpi
l4mpi

Reputation: 5149

Command line arguments to Programs are always given as strings (this is not only true for python but at least all C-related languages). This means when you give a number like "1" as an argument, you need to explicitly convert it into an integer. In your case, you could try converting it and assume it is a string if this does not work:

try:
    v = int(a)
    #... do int related stuff
except ValueError:
    #... do string related stuff

This is bad design though, it would be better to let the user decide if he wants the argument to be interpreted as a string - after all, every int given by the user is also a valid string. You could for example use something like argparse and specify two different arguments given with "-i" for int and "-s" for string.

Upvotes: 1

Related Questions