In Python, you can access command-line arguments using the sys
module. Import sys
and use sys.argv
, which is a list where:
sys.argv[0]
is the script’s name.sys.argv[1:]
contains additional arguments passed.
Example:
python
import sys
# Print all arguments
print(sys.argv)
# Access individual arguments
if len(sys.argv) > 1:
arg1 = sys.argv[1]
print(f"First argument: {arg1}")
else:
print("No arguments provided.")
For advanced argument parsing, use the argparse
module, which provides better handling and helps define optional/required arguments with descriptions. Example:
python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--name", help="Your name")
args = parser.parse_args()
print(args.name)