How can you access command line arguments in a Python program?

QuestionsQuestions4 SkillsProRun a Small ProgramSep, 08 2025
0164

You can access command line arguments in a Python program using the argparse module. Here's a simple example:

import argparse

# Create a parser object
parser = argparse.ArgumentParser(description='Process some integers.')

# Add arguments
parser.add_argument('url', type=str, help='The URL of the webpage to open')
parser.add_argument('--new-window', action='store_true', help='Open the page in a new window')

# Parse the arguments
args = parser.parse_args()

# Access the arguments
print(f'URL: {args.url}')
if args.new_window:
    print('Open in new window: Yes')
else:
    print('Open in new window: No')

To run this program, you would use a command like:

python your_program.py https://www.example.com --new-window

This will print the URL and whether the new window flag was set.

0 Comments

no data
Be the first to share your comment!