In this source code example, we will demonstrate how to read command-line arguments in Python.
Python programs can receive command-line arguments. The sys.argv contains a list of command-line arguments passed to a Python script. The argv[0] is the script name; the remaining elements are arguments passed to the script.Python command-line arguments example
The following example prints the command line arguments passed to the script.Create a command_line_arguments.py file and add the following content to it:
#!/usr/bin/env python
# command_line_arguments.py
import sys
print("Script name:", sys.argv[0])
print("Arguments:", end=" ")
for arg in sys.argv[1:]:
print(arg, end=" ")
print()
Output:
$ ./command_line_arguments.py 1 2 3
Script name: ./command_line_arguments.py
Arguments: 1 2 3
Comments
Post a Comment