Making optparse take user input. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Making optparse take user input.

https://code.sololearn.com/cEA5AwElVg7d/?ref=app How do I get user input in the second function area for address. Usually if I run without the yes and no input I can run like python3 script.py -i (interface here) -a (address here) And it'll work in the terminal and change the address. But I want to make it so after the user puts yes and continues i want an area where they can input those commands about -i and -a and run the arguments. Any ideas how to do this? This is just a small part of the code but it will all run but doesn't let me input the interface and address unless I already have values set within the code itself with predefined addresses and interfaces.

7th Aug 2019, 10:00 AM
Binary
Binary - avatar
1 Answer
+ 1
First thing, optparse library is deprecated and you should use argparse instead. (Actually they are very similar.) https://docs.python.org/3/library/argparse.html#module-argparse You did not mention if there should be any validation on the format of the arguments. So I made an example that works like this. If the user starts the script with both -i and -a arguments provided in command line, then they will be parsed. If any of them is missing, user will get asked to input them, as long as he/she does not provide a non-empty string. Another solution might be, to use the required=True parameter in parser.add_argument(). In that case the script cannot be run without providing the argument in command line. Hope that helps! https://code.sololearn.com/c0xhaK3mOvzL/#py
13th Aug 2019, 8:43 PM
Tibor Santa
Tibor Santa - avatar