Processing Command Line Arguments in Python
In Python, the command line arguments are available in a list called sys.argv. To access these arguments, use the following syntax:
import sys # Print all command line arguments print("\n".join(sys.argv)) # Print all arguments except the script name print(sys.argv[1:])
Explanation:
Example:
Let's say we have a script called my_script.py that takes a filename as an argument. We can process this argument using the following code:
import sys if len(sys.argv) < 2: print("Usage: my_script.py <filename>") exit() filename = sys.argv[1] # Do something with the filename
This code checks if the user has provided a filename and exits gracefully if not. Otherwise, it assigns the filename to a variable for further processing.
The above is the detailed content of How Do I Access and Process Command Line Arguments in Python?. For more information, please follow other related articles on the PHP Chinese website!