Skip to content

Commit a2e0042

Browse files
committed
add argparse tutorial
1 parent 51ac5aa commit a2e0042

14 files changed

+176
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,7 @@ This is a repository of all the tutorials of [The Python Code](https://www.thepy
177177
- [How to Split a String In Python](https://www.thepythoncode.com/article/split-a-string-in-python). ([code](python-standard-library/split-string))
178178
- [How to Print Variable Name and Value in Python](https://www.thepythoncode.com/article/print-variable-name-and-value-in-python). ([code](python-standard-library/print-variable-name-and-value))
179179
- [How to Make a Hangman Game in Python](https://www.thepythoncode.com/article/make-a-hangman-game-in-python). ([code](python-standard-library/hangman-game))
180+
- [How to Use the Argparse Module in Python](https://www.thepythoncode.com/article/how-to-use-argparse-in-python). ([code](python-standard-library/argparse))
180181

181182
- ### [Using APIs](https://www.thepythoncode.com/topic/using-apis-in-python)
182183
- [How to Automate your VPS or Dedicated Server Management in Python](https://www.thepythoncode.com/article/automate-veesp-server-management-in-python). ([code](general/automating-server-management))

Diff for: python-standard-library/argparse/1_simple_example.py

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import argparse
2+
3+
parser = argparse.ArgumentParser(description='A simple argparse example.')
4+
parser.add_argument('input', help='Input file to process.')
5+
6+
args = parser.parse_args()
7+
print(f'Processing file: {args.input}')
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import argparse
2+
3+
parser = argparse.ArgumentParser(description='A simple argparse example.')
4+
parser.add_argument('input', help='Input file to process.')
5+
# parser.add_argument('-o', '--output', default='output.txt', help='Output file.')
6+
parser.add_argument('-o', '--output', required=True, help='Output file.')
7+
8+
args = parser.parse_args()
9+
print(f'Processing file: {args.input}')
10+
print(f"Writing to file: {args.output}")

Diff for: python-standard-library/argparse/2.3_choices.py

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import argparse
2+
3+
parser = argparse.ArgumentParser(description='A simple argparse example.')
4+
parser.add_argument('input', help='Input file to process.')
5+
parser.add_argument('-m', '--mode', choices=['add', 'subtract', 'multiply', 'divide'], help='Calculation mode.')
6+
7+
args = parser.parse_args()
8+
print(f'Processing file: {args.input}')
9+
print(f"Mode: {args.mode}")

Diff for: python-standard-library/argparse/2.5_nargs.py

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import argparse
2+
3+
parser = argparse.ArgumentParser(description='A simple argparse example.')
4+
parser.add_argument('--values', nargs=3)
5+
# parser.add_argument('--value', nargs='?', default='default_value')
6+
# parser.add_argument('--values', nargs='*')
7+
# parser.add_argument('--values', nargs='+')
8+
9+
args = parser.parse_args()
10+
print(f"Values: {args.values}")
+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import argparse
2+
3+
parser = argparse.ArgumentParser(description='A simple argparse example.')
4+
parser.add_argument('--foo', action='store', help='Store the value of foo.')
5+
parser.add_argument('--enable', action='store_true', help='Enable the feature.')
6+
parser.add_argument('--disable', action='store_false', help='Disable the feature.')
7+
parser.add_argument('--level', action='store_const', const='advanced', help='Set level to advanced.')
8+
parser.add_argument('--values', action='append', help='Append values to a list.')
9+
parser.add_argument('--add_const', action='append_const', const=42, help='Add 42 to the list.')
10+
parser.add_argument('-v', '--verbose', action='count', help='Increase verbosity level.')
11+
args = parser.parse_args()
12+
print(f"Values: {args.values}")
13+
print(f"Verbosity: {args.verbose}")
+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import argparse
2+
3+
class CustomAction(argparse.Action):
4+
def __call__(self, parser, namespace, values, option_string=None):
5+
# Perform custom processing on the argument values
6+
processed_values = [value.upper() for value in values]
7+
8+
# Set the attribute on the namespace object
9+
setattr(namespace, self.dest, processed_values)
10+
11+
# Set up argument parser and add the custom action
12+
parser = argparse.ArgumentParser(description='Custom argument action example.')
13+
parser.add_argument('-n', '--names', nargs='+', action=CustomAction, help='A list of names to be processed.')
14+
15+
args = parser.parse_args()
16+
print(args.names)
+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import argparse
2+
3+
parser = argparse.ArgumentParser(description='A simple argparse example.')
4+
parser.add_argument("-r", "--ratio", type=float)
5+
args = parser.parse_args()
6+
print(f"Ratio: {args.ratio}")
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import argparse
2+
3+
parser = argparse.ArgumentParser(description='A subcommand example.')
4+
subparsers = parser.add_subparsers(help='Subcommand help')
5+
6+
list_parser = subparsers.add_parser('list', help='List items')
7+
add_parser = subparsers.add_parser('add', help='Add an item')
8+
add_parser.add_argument('item', help='Item to add')
9+
10+
args = parser.parse_args()

Diff for: python-standard-library/argparse/4.1_file_renamer.py

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import argparse
2+
import os
3+
4+
# Rename function
5+
def rename_files(args):
6+
# Your file renaming logic here
7+
print(f"Renaming files in {args.path}...")
8+
print(f"Prefix: {args.prefix}")
9+
print(f"Suffix: {args.suffix}")
10+
print(f"Replace: {args.replace}")
11+
os.chdir(args.path)
12+
for file in os.listdir():
13+
# Get the file name and extension
14+
file_name, file_ext = os.path.splitext(file)
15+
# Add prefix
16+
if args.prefix:
17+
file_name = f"{args.prefix}{file_name}"
18+
# Add suffix
19+
if args.suffix:
20+
file_name = f"{file_name}{args.suffix}"
21+
# Replace substring
22+
if args.replace:
23+
file_name = file_name.replace(args.replace[0], args.replace[1])
24+
# Rename the file
25+
print(f"Renaming {file} to {file_name}{file_ext}")
26+
os.rename(file, f"{file_name}{file_ext}")
27+
28+
# custom type for checking if a path exists
29+
def path_exists(path):
30+
if os.path.exists(path):
31+
return path
32+
else:
33+
raise argparse.ArgumentTypeError(f"Path {path} does not exist.")
34+
35+
36+
# Set up argument parser
37+
parser = argparse.ArgumentParser(description='File renaming tool.')
38+
parser.add_argument('path', type=path_exists, help='Path to the folder containing the files to rename.')
39+
parser.add_argument('-p', '--prefix', help='Add a prefix to each file name.')
40+
parser.add_argument('-s', '--suffix', help='Add a suffix to each file name.')
41+
parser.add_argument('-r', '--replace', nargs=2, help='Replace a substring in each file name. Usage: -r old_string new_string')
42+
43+
args = parser.parse_args()
44+
45+
# Call the renaming function
46+
rename_files(args)
+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import argparse
2+
3+
# Operation functions
4+
def add(args):
5+
print(args.x + args.y)
6+
7+
def subtract(args):
8+
print(args.x - args.y)
9+
10+
def multiply(args):
11+
print(args.x * args.y)
12+
13+
def divide(args):
14+
print(args.x / args.y)
15+
16+
# Set up argument parser
17+
parser = argparse.ArgumentParser(description='Command-line calculator.')
18+
subparsers = parser.add_subparsers()
19+
20+
# Add subcommands
21+
add_parser = subparsers.add_parser('add', help='Add two numbers.')
22+
add_parser.add_argument('x', type=float, help='First number.')
23+
add_parser.add_argument('y', type=float, help='Second number.')
24+
add_parser.set_defaults(func=add)
25+
26+
subtract_parser = subparsers.add_parser('subtract', help='Subtract two numbers.')
27+
subtract_parser.add_argument('x', type=float, help='First number.')
28+
subtract_parser.add_argument('y', type=float, help='Second number.')
29+
subtract_parser.set_defaults(func=subtract)
30+
31+
multiply_parser = subparsers.add_parser('multiply', help='Multiply two numbers.')
32+
multiply_parser.add_argument('x', type=float, help='First number.')
33+
multiply_parser.add_argument('y', type=float, help='Second number.')
34+
multiply_parser.set_defaults(func=multiply)
35+
36+
divide_parser = subparsers.add_parser('divide', help='Divide two numbers.')
37+
divide_parser.add_argument('x', type=float, help='First number.')
38+
divide_parser.add_argument('y', type=float, help='Second number.')
39+
divide_parser.set_defaults(func=divide)
40+
41+
args = parser.parse_args()
42+
args.func(args)

Diff for: python-standard-library/argparse/README.md

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# [How to Use the Argparse Module in Python](https://www.thepythoncode.com/article/how-to-use-argparse-in-python)
2+
The `argparse` module in Python is a built-in module that helps us to parse command-line arguments. It is a very useful module that allows us to easily write user-friendly command-line interfaces. In this tutorial, we will learn how to use the `argparse` module in Python.
3+
4+
The code is available for each section, so you can run it and see the output.

Diff for: python-standard-library/argparse/data/item1.txt

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
This is a text file

Diff for: python-standard-library/argparse/data/item2.txt

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Another text file is created in the same directory as the original file.

0 commit comments

Comments
 (0)