Friday, January 17, 2025
HomeProgrammingHow do I access command line arguments? - python

How do I access command line arguments? – python

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)
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x