Apt command line interface-like yes/no input?
To create an APT-like yes/no prompt in Python, employ input()
in a concise while
loop:
This script is a efficient way to solicit, verify, and act based on user input.
Diving deeper // Upgrading your script's experience
When coding user-friendly CLI applications, it's important to predict user behavior to create a seamless experience. Here are a few strategies to optimize your code and provide a near-APT level of interaction.
Just press Enter: strtobool
If you want to emulate APT's functionality where pressing Enter defaults to 'yes', then you're in luck! Python's strtobool
function can handle this for you:
Note how this function elegantly handles empty inputs and provides default responses.
Cross-platform compatibility with Click
When you need your CLI application to work reliably across platforms, the Click
library is your friend:
With Click
's confirm()
, you get a higher level of abstraction, making your script more readable and Pythonic. And it takes care of cross-platform quirks - because no one wants to debug why 'Yes' doesn't mean 'yes' on a random OS.
Functionality // Making your script modular
Sometimes it's not about making the code work. It's about making the code work harder for you. Let's take our Y/N prompt script and turn it into a function:
Modularity is key to maintainability. Plus, it makes the script ready for your next coding adventure.
Handling edge cases
To boldly cut beautiful code, you need to prepare for edge cases like:
- The user enters 'Kumquat' instead of 'Yes' or 'No'
- The user presses Enter without typing in anything
- The user enters 'YES' instead of 'yes'
Our previous script examples handle these oddities by using lower()
to make everything lowercase and dealing with blank responses.
Offering better feedback
Make your error messages immediate and helpful to improve user experience:
Good feedback guides users to the correct responses.
Abstraction time?
If your yes/no prompt keeps cropping up in your scripts, or if you find yourself adding more features to it, it might be time to move it into its own module.
Was this article helpful?