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?
import sys
def main():
input1 = sys.argv[1]
input2 = sys.argv[2]
...
if __name__ == "__main__":
main()
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.
There are two options.
sys.argv
and use that.getopts
See also: Dive into Python and PMotW
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With