Let's say I have this script.
#!/usr/bin/env python
from sys import argv
filename, value1, value2 = argv
print value1 + value2
Now, I want the two variables, value1 and value2 to be passed as integers. Right now when I run this in my command line I would get something like this.
pi@raspberrypi -/Desktop $ python test.py 2 2
22
I want something like this to happen.
pi@raspberrypi -/Desktop $ python test.py 2 2
4
How can I do this?
Convert your arguments to integers.
import sys
value1, value2 = (int(x) for x in sys.argv[1:])
This of course assumes that your are expecting exactly two arguments which can be converted to integers.
If you ever want to pass an arbitrary number of integers, you can get a list of them with
argnums = [int(x) for x in sys.argv[1:]]
Also, if you ever plan to write a serious command line interface, consider using argparse.
Everything on argv are strings. You need to manually convert them as integers, like:
value1 = int(argv[1])
value2 = int(argv[2])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With