Numbers passed as command line arguments in python not interpreted as integers

前端 未结 6 1079
有刺的猬
有刺的猬 2020-12-10 10:42

I am familiar with C, and have started experimenting in python. My question is regarding the sys.argv command. I\'ve read it is used for a command line interpre

相关标签:
6条回答
  • 2020-12-10 10:47

    You can convert the arguments to integers using int()

    import sys
    
    a = int(sys.argv[1])  b = int(sys.argv[2])
    
    print a, b
    
    print a+b
    

    input: python mySum.py 100 200

    output:

    100 200
    300
    
    0 讨论(0)
  • 2020-12-10 10:52

    You also should validate the user input:

    import sys
    
    def is_intstring(s):
        try:
            int(s)
            return True
        except ValueError:
            return False
    
    for arg in sys.argv[1:]:
        if not is_intstring(arg):
            sys.exit("All arguments must be integers. Exit.")
    
    numbers = [int(arg) for arg in sys.argv[1:]]
    sum = sum(numbers)
    
    print "The sum of arguments is %s" % sum
    
    0 讨论(0)
  • 2020-12-10 10:57

    Indeed, you have found the problem yourself, sys.argv is an array of strings.

    You can transform a string to an integer with int(). In this case for example: a = int(sys.argv[1])

    0 讨论(0)
  • 2020-12-10 11:10

    Beware of performing comparisons involving command-line arguments, which can lead to really unexpected behavior owing to Python 2's policy for comparing objects of different types ('int' < 'list' < 'string' < 'tuple') as noted here. In Python 3, comparing objects of different types will lead to a TypeError.

    For an example of object comparison mayhem, try removing the int() call in section 6.1.1. of the Python tutorial Fibonacci code and you'll get an infinite loop, since the while loop condition becomes: 'int' < 'string'. (This would not happen in Perl, btw).

    Great advice from @Jan-Philip above to validate command-line arguments, even for Python 3.

    0 讨论(0)
  • 2020-12-10 11:13

    sys.argv items are always strings. you should cast them to int with int(a).

    You can also use third party libraries for handling CLI arguments such as OptParse.

    0 讨论(0)
  • 2020-12-10 11:13

    In Python, strings are not implicitly converted to integers. Try

    num1 = int(sys.argv[1])
    This would represent the numerical value of the number, not its string representation.
    
    0 讨论(0)
提交回复
热议问题