Alright ! Let’s talk about command line options in Python those little flags that make our lives easier when running programs from the terminal. With Python, you have tons of customizable options at your disposal to tailor how a program runs without having to edit its source code.
Let me give you an example. Let’s say we want to run a script called “my_script.py”. By default, it prints out some text and then exits. But what if we wanted to change the output format or add extra arguments? That’s where command line options come in!
Here’s an example of how you might use Python’s built-in argparse module to create a script with customizable options:
# Import the argparse module to handle command line arguments
import argparse
# Define the main function
def main():
# Create an ArgumentParser object with a description
parser = argparse.ArgumentParser(description='A simple script that does stuff')
# Add a positional argument for the input file path
parser.add_argument('input', type=str, help='The input file path')
# Add an optional argument for the output file path, with a default value of "stdout"
parser.add_argument('-o', '--output', type=str, default="stdout", help='Output file path (default: stdout)')
# Parse the arguments and store them in a variable
args = parser.parse_args()
# Do stuff with the arguments here...
# For example, print out the input and output file paths
print("Input file path:", args.input)
print("Output file path:", args.output)
# Check if the script is being run directly
if __name__ == "__main__":
# Call the main function
main()
# Output:
# python script.py input_file -o output_file
# Input file path: input_file
# Output file path: output_file
# Explanation:
# The script uses the argparse module to handle command line arguments.
# The main function is defined to contain the code that will be executed.
# An ArgumentParser object is created with a description.
# A positional argument is added for the input file path, with a type of string and a help message.
# An optional argument is added for the output file path, with a type of string, a default value of "stdout", and a help message.
# The arguments are parsed and stored in a variable.
# The main function is called if the script is being run directly.
# Inside the main function, the input and output file paths are printed out using the arguments that were parsed.
In this example, we’re using argparse to create a script that takes an input file path and optionally outputs the results to a specified output file. The `-o`, or `–output` flag is optional and has a default value of “stdout” (which means it will print to the console).
To run this script, you would save it as “my_script.py”, navigate to its directory in your terminal, and then type:
#!/bin/bash # This line specifies the interpreter to be used for executing the script
# This script takes an input file and optionally outputs the results to a specified output file.
# The `-o` or `--output` flag is optional and has a default value of "stdout" (which means it will print to the console).
# To run this script, you would save it as "my_script.sh", navigate to its directory in your terminal, and then type:
# bash my_script.sh input.txt -o output.txt
# The following line checks if the number of arguments passed is less than 2 (input file is missing)
if [ $# -lt 2 ]; then
echo "Error: Missing input file."
exit 1 # This line exits the script with an error code of 1
fi
# The following line checks if the input file exists
if [ ! -f $1 ]; then
echo "Error: Input file does not exist."
exit 1 # This line exits the script with an error code of 1
fi
# The following line checks if the output file is specified using the `-o` or `--output` flag
if [ "$2" == "-o" ] || [ "$2" == "--output" ]; then
output_file=$3 # This line assigns the third argument to the variable `output_file`
else
output_file="stdout" # This line sets the default value of `output_file` to "stdout"
fi
# The following line executes the python script with the input and output file arguments
python my_script.py $1 -o $output_file
# The following line checks if the python script executed successfully
if [ $? -eq 0 ]; then
echo "Script executed successfully."
else
echo "Error: Script execution failed."
fi
This would run our Python script with the specified input file path (“input.txt”) and output it to “output.txt”. If you didn’t specify an output file, it would print to the console instead (since that’s the default).
There are tons more options available for customizing your scripts and making them easier to use. But hey, we’re not here to bore you with all the details! Just remember that command line options can be your best friend when working with complex programs or scripts just don’t get too carried away!
In addition to using argparse to create customizable options for our Python scripts, it’s also important to provide consistent status codes in our CLI applications. This allows us and our users to successfully integrate our apps into shell scripting and command pipes. To check how your app behaves now, go ahead and run the following commands:
# This script is used to run a Python script with customizable options and consistent status codes for CLI applications.
# It allows for successful integration into shell scripting and command pipes.
# The first command runs the Python script "my_script.py" with the input file "input.txt" as an argument.
python my_script.py input.txt
# The following command checks for the existence of a target directory before running the Python script.
# If the directory does not exist, the script will not run.
# This ensures that the script does not encounter any errors and can successfully complete its task.
python my_script.py nonexistent-directory
The app terminates its execution immediately when the target directory doesnt exist, and you can inspect $? or $LASTEXITCODE to confirm that your app has returned 1 to signal an error in its execution. Providing consistent status codes is a best practice for CLI applications!