0

I want to pass some integer values into an array via sys.argv, but I get a TypeError. how can I pass integers into my array, from the argv list? Must I do an explicit conversion?

#!/usr/bin/python
from array import array
import serial, sys

ser = serial.Serial('/dev/ttyACM0', 9600)
a=array('i',(0 for i in range(1, 3)))

a.append(sys.argv[1])
a.append(sys.argv[2])
a.append(sys.argv[3])

print(a.range(0-2))

Here is the Error:

$ ./a.py 2 3 4
Traceback (most recent call last):
  File "./a.py", line 8, in <module>
    a.append(sys.argv[1])
TypeError: an integer is required

I get that array('i') is an array of ints, and that sys.argv is a list item. I just dont know how to get sys.argv to become an int.

j0h
  • 1,675
  • 6
  • 27
  • 50
  • 4
    I don't know what you expect `a.range(0-2)` to do, but the rest can be done in one line: `a = array('i', map(int, sys.argv[1:4]))`. Python is **strongly typed**, it doesn't do implicit conversions. – jonrsharpe Dec 02 '14 at 13:36

1 Answers1

2

Replace:

a.append(sys.argv[1])
a.append(sys.argv[2])
a.append(sys.argv[3])

with:

a.append(int(sys.argv[1]))
a.append(int(sys.argv[2]))
a.append(int(sys.argv[3]))

and this:

print(a.range(0-2))

with:

print(a[0:2]) # or print(a) 

otherwise it will throw another error.

Irshad Bhat
  • 8,479
  • 1
  • 26
  • 36