In Python, you can access command-line arguments using the sys.argv
list from the sys
module. The first element, sys.argv[0]
, is the script name, and subsequent elements are the arguments passed to the script.
python
import sys
print(sys.argv) # Prints all command-line arguments as a list
To handle arguments more robustly, use the argparse
module:
python
import argparse
parser = argparse.ArgumentParser(description="Example script")
parser.add_argument("--name", help="Your name")
args = parser.parse_args()
print(args.name)
This approach allows better parsing, validation, and help messages, making it ideal for complex scripts.