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
  • 190,037
  • 45
  • 260
  • 285
Richard
  • 14,058
  • 30
  • 82
  • 108

4 Answers4

9
import sys

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

if __name__ == "__main__":
   main()
froadie
  • 75,789
  • 72
  • 163
  • 232
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
  • 17,337
  • 12
  • 80
  • 104
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
  • 386,424
  • 207
  • 554
  • 861
Sean Vieira
  • 148,604
  • 32
  • 306
  • 290
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
  • 6