tags:

views:

54

answers:

5

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?

+5  A: 

http://stackoverflow.com/questions/1009860/command-line-arguments-in-python for serious command line argument handling.

use sys.argv for simple access:

http://www.faqs.org/docs/diveintopython/kgp_commandline.html

jkerian
+1 for the great Stackoverflow link
Sean Vieira
+1  A: 

There are two options.

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

See also: Dive into Python and PMotW

Sean Vieira
+2  A: 

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.

Fabian
+1  A: 
import sys

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

if __name__ == "__main__":
   main()
froadie