Skip to content

Q&A · Answered

How to read command line arguments in Python

asked 9 months, 1 week ago 2086 views 1 answer
13

How can I pass and read command line arguments in a Python script?

1 Answer

One accepted
6

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago

Using sys.argv

import sys

# sys.argv[0] is the script name
script_name = sys.argv[0]
arg1 = sys.argv[1]  # First argument

Using argparse (recommended)

import argparse

parser = argparse.ArgumentParser(description='My script')
parser.add_argument('--name', type=str, required=True,
                    help='Your name')
parser.add_argument('--verbose', '-v', action='store_true',
                    help='Verbose output')
parser.add_argument('--count', type=int, default=1,
                    help='Number of iterations')

args = parser.parse_args()
print(f"Hello, {args.name}")

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.