6

I am wondering how would one get variables inputted in a python script while opening from cmd prompt? I know using c one would do something like:

int main( int argc, char **argv ) {
    int input1 = argv[ 0 ]
    int input2 = argv[ 1 ]

.....

}

how can I achieve the same kind of result in python?

William Pursell
  • 204,365
  • 48
  • 270
  • 300
Richard
  • 15,152
  • 31
  • 85
  • 111

4 Answers4

9
import sys

def main():
   input1 = sys.argv[1]
   input2 = sys.argv[2]
...

if __name__ == "__main__":
   main()
froadie
  • 79,995
  • 75
  • 166
  • 235
3

The arguments are in sys.argv, the first one sys.argv[0] is the script name.

For more complicated argument parsing you should use argparse (for python >= 2.7). Previous modules for that purpose were getopts and optparse.

Mad Scientist
  • 18,090
  • 12
  • 83
  • 109
1

There are two options.

  1. import sys.argv and use that.
  2. Use getopts

See also: Dive into Python and PMotW

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
0

it is also useful to determine option specific variables

''' \
USAGE:  python script.py -i1 input1 -i2 input2
    -i1 input1 : input1 variable
    -i2 input2 : input2 variable
'''

import sys 
...

in_arr = sys.argv
if '-i1' not in in_arr  or '-i2' not in in_arr:
    print (__doc__)
    raise NameError('error: input options are not provided')
else:
    inpu1 = in_arr[in_arr.index('-i1') + 1]
    inpu2 = in_arr[in_arr.index('-i2') + 1]
...

# python script.py -i1 Input1 -i2 Input2
Trigremm
  • 61
  • 7