Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to input variable into a python script while opening from cmd prompt?

Tags:

python

input

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?

like image 897
Richard Avatar asked Aug 26 '10 16:08

Richard


3 Answers

import sys

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

if __name__ == "__main__":
   main()
like image 192
froadie Avatar answered Nov 14 '22 23:11

froadie


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.

like image 34
Mad Scientist Avatar answered Nov 14 '22 23:11

Mad Scientist


There are two options.

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

See also: Dive into Python and PMotW

like image 40
Sean Vieira Avatar answered Nov 14 '22 23:11

Sean Vieira