How to enter variable in python script when opening cmd from command line?

I am wondering how to get variables entered in python script when opening cmd from command line? I know using c you would do something like:

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

.....

}

how can i achieve the same result in python?

+3
source share
6 answers
import sys

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

if __name__ == "__main__":
   main()
+7
source

Command Line Arguments In Python, for serious handling of command line arguments.

use sys.argv for easy access:

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

+5
source

sys.argv, sys.argv[0] - script.

argparse ( python >= 2.7). getopts optparse.

+2
source

There are two options.

See also: Dive in Python and PMotW

+1
source

it is also useful to define optional 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
0
source

Source: https://habr.com/ru/post/1761766/


All Articles