Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run script with integer arguments

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?

like image 467
Vladimir Putin Avatar asked Nov 03 '25 12:11

Vladimir Putin


2 Answers

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.

like image 123
timgeb Avatar answered Nov 05 '25 00:11

timgeb


Everything on argv are strings. You need to manually convert them as integers, like:

value1 = int(argv[1])
value2 = int(argv[2])
like image 20
vz0 Avatar answered Nov 05 '25 01:11

vz0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!