This tutorial will guide you through the process of passing a list as a command-line argument in Python.
Command-line arguments are an essential aspect of programming as they can determine the behavior of a script at runtime. When it comes to command-line arguments, Python’s built-in sys module allows scripts to take various forms of input from the command line.
However, passing a list can be tricky as sys.argv treats all inputs as strings. Don’t worry, though – the process is quite simple once you understand how it works. Let’s delve into the steps.
Step 1: Importing Necessary Libraries
The first step is to import the necessary libraries. It involves importing the sys and ast modules. The “sys” module allows you to use command-line arguments, and the “ast” module enables you to convert command-line strings into a list.
1 2 |
import sys import ast |
Step 2: Script for Accepting Input
To pass a list as a command-line argument in Python, the list has to be passed as a string. Here’s an example:
1 |
python my_script.py "[1, 2, 3]" |
This command-line input can be accessed with sys.argv (a list in Python, which contains the command-line arguments passed to the script).
1 |
input_list = sys.argv[1] |
Step 3: Converting a String to a Python List
Even though you’ve passed a list as an argument to your Python script, it’s interpreted as a string. Hence, to use it like a list in the script, you need to convert it back into a list. This is where the ast module’s literal_eval function is utilized. This function safely parses an expression node or a string containing a Python expression and then returns the result as a list.
1 |
actual_list = ast.literal_eval(input_list) |
You should now have a Python list from your command-line argument that you can use in your script.
Full Code
1 2 3 4 5 6 7 8 |
import sys import ast # get the command line argument as a string input_list = sys.argv[1] # safely evaluate the string to a list actual_list = ast.literal_eval(input_list) |
Note
If incorrect data is passed through the command line (not a list or other unsafe commands), ast.literal_eval will raise an exception. Always make sure that the PEP 572 compliant inputs are passed to your script.
Conclusion
In this tutorial, you’ve learned how to pass a list as a command-line argument in Python using the modules sys and ast. You should now be able to input lists from the command line into your Python scripts, which is an important skill for more advanced Python scripting.
Remember to ensure that the input passed is always safe to prevent potential run-time issues.