In Python, command-line arguments can be extremely beneficial when you wish to provide some command for your script while executing it. These arguments can be received in the running script as variables and used accordingly.
They can be anything from files to data strings. Today we are going to learn how to pass a filename as a command line argument in Python.
Step 1: Understand the Concept of Command Line Arguments
First off, let’s understand what command-line arguments are. Command-line arguments are strings of text used in the command prompt to change the behavior of the script.
These arguments are passed at the time of executing the script, and accessible through the built-in sys module in Python.
The system module includes many facilities to use within the Python environment. To specifically access the command line arguments, we use sys.argv.
Step 2: Using sys.argv
In Python, the command-line arguments are stored in sys.argv, which is a list in Python. The first item of this list, sys.argv[0], is always the name of the script itself. And if you are passing any arguments for your script, those are saved in sys.argv[1], sys.argv[2], and so on.
Step 3: Importing the Required Modules
Before we can use sys.argv, we must first import the necessary system module. This is done by using the import command as below:
1 |
import sys |
Step 4: Writing the Script to Accept the Filename as an Argument
Now let’s write a simple script that accepts a filename as a command-line argument, and then reads and prints the content of that file.
1 2 3 4 5 6 7 8 9 10 11 12 |
import sys # Check if filename is passed if len(sys.argv) > 1: filename = sys.argv[1] try: with open(filename, 'r') as f: print(f.read()) except FileNotFoundError: print('File not found.') else: print('Filename not provided.') |
Here, we first check if the filename has been passed (as sys.argv will always have at least one item i.e., the script’s name). If it is provided, we attempt to open the file and print its content else an error message is printed.
Step 5: Executing the script with the filename as an argument
You can execute the script with the filename as argument on the command line as so:
$ python script.py textfile.txt
Here, ‘script.py’ is your script’s name, and ‘textfile.txt’ is the filename you wish to pass as the command line argument.
Final script
1 2 3 4 5 6 7 8 9 10 11 |
import sys if len(sys.argv) > 1: filename = sys.argv[1] try: with open(filename, 'r') as f: print(f.read()) except FileNotFoundError: print('File not found.') else: print('Filename not provided.') |
Conclusion
This tutorial is intended to assist you in understanding how to pass a filename as a command line argument in Python, and how to use it in your script.
Command line arguments can be beneficial in many scenarios, particularly when automating tasks or when needing to change the behavior of a script dynamically on execution.