Passing arguments to a python program

  • 8 months ago
Comment

ChatGPT
1 / 1

Passing arguments to a Python program can be done using the command line when you run the program. Python provides the sys.argv list that contains the command-line arguments passed to the script.

Here's how you can pass and access command-line arguments in a Python program:

  1. Using sys.argv:
python
import sys

# sys.argv[0] is the script name itself
script_name = sys.argv[0]
arguments = sys.argv[1:] # Get all arguments excluding the script name

print("Script name:", script_name)
print("Arguments:", arguments)

You can run the script from the command line like this:

bash
python script.py arg1 arg2 arg3
  1. Using argparse (Recommended for complex argument handling):

The argparse module provides a more structured and powerful way to handle command-line arguments. It allows you to define argument types, default values, descriptions, and more.

python
import argparse

parser = argparse.ArgumentParser(description='Process some arguments.')
parser.add_argument('arg1', type=int, help='First argument')
parser.add_argument('--arg2', type=str, default='default_value', help='Second argument (optional)')
parser.add_argument('--flag', action='store_true', help='Flag argument')

args = parser.parse_args()

print("arg1:", args.arg1)
print("arg2:", args.arg2)
print("flag:", args.flag)

You can run the script with arguments:

bash
python script.py 123 --arg2 custom_value --flag
  1. Using sys.stdin (Piping input):

You can also pass input to the script using pipes and sys.stdin. This is useful when you want to pass data from one command to another.

bash
echo "Hello, World!" | python script.py

In your Python script:

python
import sys

data = sys.stdin.read()
print("Input data:", data)

These are some common ways to pass arguments to a Python program. Depending on your needs, you can choose the appropriate method. If you have complex argument handling requirements, using the argparse module is recommended.