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?

1
  • You should probably check so that the number of arguments are at least 2 before trying to read to input2. Commented Jan 22, 2014 at 10:00

4 Answers 4

9
import sys

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

if __name__ == "__main__":
   main()
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

1

There are two options.

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

See also: Dive into Python and PMotW

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.