If you have been diving into the convenience and power of Python programming, you have probably come across concepts like arguments and inputs. These are integral parts of almost any Python script as they let the user interact with your code, providing it with necessary data and changing its behavior according to their needs. However, have you learned to make use of Python command line input yet? Today’s tutorial will focus on this very subject, introducing you to an even more flexible way of interacting with your Python scripts – directly from the command line!
Table of contents
So, What’s Python Command Line Input?
Command Line Input in Python is a technique by which the user can pass values for variables directly from the terminal when calling the script. This technique eliminates the need for user input mid-script and allows all data to be provided upfront.
What’s It For?
Python command line input holds a few handy utilities:
- It enables script testing with different values quickly and efficiently.
- It makes your Python scripts more modular and able to interface with other scripts or programs.
- It enables a user to dictate the behavior of the script directly when calling it, vital for batch operations and automation.
Why Should You Learn It?
As a Python coder, understanding command line inputs is key to producing powerful, flexible scripts that are ready for real-world usage. Whether you’re scripting for data analysis or game mechanics, the ability to control your code’s operation without hard coding variables opens up tremendous possibilities. By the end of this tutorial, you’ll understand how to implement this skill in Python, adding a versatile tool to your coding arsenal.
Using the sys Module
First off, Python’s built-in sys module provides access to command line arguments using sys.argv, an array representing all the command-line data. Let’s look at a simple example of this.
First, write a Python file called example1.py:
import sys print("Number of arguments:", len(sys.argv)) print("Argument List:", str(sys.argv))
Now, run this script from the terminal with some command line arguments:
$ python3 example1.py arg1 arg2 arg3
You should see output like this:
Number of arguments: 4 Argument List: ['example1.py', 'arg1', 'arg2', 'arg3']
Accessing Individual Arguments
Arguments can also be accessed individually just as you would with any other array. Let’s modify example1.py to implement this:
import sys print("Script Name:", sys.argv) print("First argument:", sys.argv) print("Second argument:", sys.argv) print("Third argument:", sys.argv)
Try running it just like before, and notice the output this time:
$ python3 example1.py arg1 arg2 arg3
The result will be something like this:
Script Name: example1.py First argument: arg1 Second argument: arg2 Third argument: arg3
Type of Command Line Arguments
The sys.argv command line arguments are always stored as strings. This means, if you’re expecting a numerical value from the command line, you’ll need to convert the string to the relevant type:
import sys first_arg_as_num = int(sys.argv) print(first_arg_as_num + 5)
$ python3 example1.py 10
This will output 15, proving that the string was successfully converted to an integer.
Remember that trying to perform a numeric operation on a string without conversion will result in a TypeError!
Handling Variable Number of Arguments
Often, you’ll not know beforehand how many arguments a user might pass. The following script dynamically handles any number of arguments by iterating over the sys.argv array:
import sys for arg in sys.argv[1:]: print("Argument:", arg)
$ python3 example1.py arg1 arg2 arg3 arg4 arg5
Each passed argument is output on its own line, demonstrating that an arbitrary number of arguments can be smoothly handled.
Validating Command Line Input
Command line inputs are externally supplied user data and, just like with other forms of user input, should be treated carefully. This includes validating the input before applying any operations.
Suppose you require strictly numerical input. Here’s how to check and notify the user if the input is inappropriate:
import sys if not sys.argv.isdigit(): print("Only numerical input is accepted!") else: num = int(sys.argv) print(num + 5)
$ python3 example1.py 10
Correct input will give a result of 15 while non-numerical input will display a prompt for numerical input only.
Handling Command Line Flags
Sometimes, you’ll need a more sophisticated command-line interface that includes optional “flags”. Python’s built-in argparse module makes constructing such complex command-line interfaces a breeze:
import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)') args = parser.parse_args() print(args.accumulate(args.integers))
In this code, the argparse library is used to succinctly specify that our script should accept an optional –sum flag, which, if provided, changes the script’s behavior to sum the integers provided after the flag instead of finding the maximum.
Parsing Named Command Line Arguments
The argparse module can also parse named arguments, not just flags:
import argparse parser = argparse.ArgumentParser() parser.add_argument("--user") args = parser.parse_args() print("Hello, " + args.user)
$ python3 example1.py --user John
Running this script with the above command will print Hello, John.
There you go! By now, you should have a firm grip on using command-line inputs in Python, making your scripts more flexible, dynamic, and user friendly. Don’t hesitate to dive in and start restructuring your scripts and operations to fully harness the power of command line inputs!
Fuel Your Python Journey with Zenva Academy
Your discovery of Python’s strength should never end – but where might you go from here? Allow us to introduce what we at Zenva consider a most suitable choice: our Python Mini-Degree.
Zenva Academy offers a broad array of more than 250 meticulously crafted online courses designed to propel your career forward. We cater to different learning levels, from absolute beginners to professionals looking to augment their knowledge.
Python Mini-Degree: From Coding Basics to Building Real-World Applications
Our Python Mini-Degree comprises a comprehensive collection of Python programming courses, starting from the very basics all the way to object-oriented programming, game development, and app creation.
This program ensures that you learn Python inside-out by applying your knowledge to actual projects. You’ll be coding your own games, algorithms, and real-world applications right from the start. Add these to your portfolio as testament to the skills you’ve honed.
One of Python’s most powerful aspects is its versatility – it’s broadly employed across various industries, including data science, machine learning, and even robotics. Hence, the goal of our Python Mini-Degree is not only to help you obtain Python mastery but also to equip you with the confidence and expertise necessary to tackle real-world projects.
All our courses are flexible and accessible 24/7, which ensures that you can learn at your own pace. To reinforce acquired knowledge, we have supplemented each course with interactive lessons, coding challenges, and quizzes.
Our Python Courses: For Every Aspirant, For Every Level
Learn to code, create games, and earn certificates that validate your ever-growing competencies. Experienced programmers can find resources to augment your proficiency even further. With Zenva’s Python Courses, explore broader content – from beginner to professional – to help you embark on your desired career path.
Whether your aim is getting your dream job, launching your game, becoming a data scientist, or starting your own venture, we at Zenva Academy are determined and delighted to help you achieve your goals.
Getting comfortable with command-line inputs in Python doesn’t just elevate your Python skills – it opens a wealth of new possibilities for your scripts, transforming how you interact with users and other programs. By making your scripts more flexible, you bridge the gaps between conventional inputs, batch operations, and full automation, making Python even more powerful and valuable in your toolbox.
We at Zenva Academy are passionate about helping learners like you get the most out of your programming journey. Whether you’re a newbie eager to dive into Python basics or a professional seeking to augment your skills, our Python Mini-Degree is tailored to guide you from foundations to complex Python constructs.+
FINAL DAYS: Unlock coding courses in Unity, Unreal, Python, Godot and more.