Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables at runtime

Tags:

python

I wish to pass in some variables into python during run time

python add2values.py 123 124

then in the python script it will take those 2 values and add together.

OR

python add2values.py a=123 b=124

then in the python script it will take those 2 values and add together.

like image 793
seesee Avatar asked Jul 24 '26 06:07

seesee


2 Answers

You can use sys.argv

test.py

#!/usr/bin/env python

import sys
total = int(sys.argv[1]) +  int(sys.argv[2])
print('Argument List: %s' % str(sys.argv))
print('Total : %d' % total)  

Run the following command:

$ python test.py 123 124
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']
Total : 247
like image 158
Adem Öztaş Avatar answered Jul 25 '26 20:07

Adem Öztaş


There are a few ways to handle command-line arguments.

One is, as has been suggested, sys.argv: an array of strings from the arguments at command line. Use this if you want to perform arbitrary operations on different kinds of arguments. You can cast the first two arguments into integers and print their sum with the code below:

import sys
n1 = sys.argv[1]
n2 = sys.argv[2]

print (int(n1) + int(n2))

Of course, this does not check whether the user has input strings or lists or integers and gives the risk of a TypeError. However, for a range of command line arguments, this is probably your best bet - to manually take care of each case.

If your script/program has fixed arguments and you would like to have more flexibility (short options, long options, help texts) then it is worth checking out the optparse and argparse (requires Python 2.7 or later) modules. Below are some snippets of code involving these two modules taken from actual questions on this site.

import argparse

parser = argparse.ArgumentParser(description='my_program')
parser.add_argument('-verbosity', help='Verbosity', required=True)

optparse, usable with earlier versions of Python, has similar syntax:

from optparse import OptionParser

parser = OptionParser()
...
parser.add_option("-m", "--month", type="int",
              help="Numeric value of the month", 
              dest="mon")

And there is even getopt if you prefer C-like syntax...

like image 37
icedwater Avatar answered Jul 25 '26 19:07

icedwater