Python Command Line Arguments Examples

‮‬https://www.lautturi.com
Python Command Line Arguments Examples

Command line arguments are a way to pass information to a command or program when it is executed from the command line. In Python, you can use the argparse module to parse command line arguments.

Here's an example of how to use the argparse module to parse command line arguments in a Python script:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-n", "--name", help="name of the user")
parser.add_argument("-a", "--age", help="age of the user", type=int)

args = parser.parse_args()

print(f"Name: {args.name}")
print(f"Age: {args.age}")

To run this script, you can use the following command:

$ python script.py -n John -a 30

This will print the following output:

Name: John
Age: 30

You can also use the argparse module to specify default values for command line arguments. For example:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-n", "--name", default="John", help="name of the user")
parser.add_argument("-a", "--age", default=30, help="age of the user", type=int)

args = parser.parse_args()

print(f"Name: {args.name}")
print(f"Age: {args.age}")

In this example, the default value for the name argument is John and the default value for the age argument is 30. If you run the script without specifying these arguments, it will use the default values.

It's important to note that this is just one example of how to use the argparse module to parse command line arguments in Python. The specific steps may vary depending on your requirements and the complexity of your command line arguments. Consult the argparse documentation and online resources for more information on how to use this module to parse command line arguments in Python.

Created Time:2017-10-30 14:27:12  Author:lautturi