[TIPS] Python Argument Parser - Bad Practices

By khoanc, at: 11:28 Ngày 18 tháng 10 năm 2024

Thời gian đọc ước tính: 6 min read

[TIPS] Python Argument Parser - Bad Practices
[TIPS] Python Argument Parser - Bad Practices

Bad Practices When Passing Arguments in Python Scripts

 

1. Using sys.argv Directly

import sys

def main():
    if len(sys.argv) < 3:
        print("Not enough arguments!")
        return
    
    arg1 = sys.argv[1]
    arg2 = sys.argv[2]
    
    if arg1 == 'option1':
        print(f"Option 1 selected with value {arg2}")
    elif arg1 == 'option2':
        print(f"Option 2 selected with value {arg2}")
    else:
        print("Unknown option!")

if __name__ == "__main__":
    main()


Bad Practice: Directly using sys.argv for parsing arguments can be error-prone and difficult to maintain.

Fix: Use the argparse module for parsing arguments. It provides a more robust and user-friendly way to handle command-line arguments.

import argparse

def main():
    parser = argparse.ArgumentParser(description="A sample argument parser.")
    parser.add_argument('arg1', type=str, help="First argument")
    parser.add_argument('arg2', type=str, help="Second argument")
    args = parser.parse_args()
    
    if args.arg1 == 'option1':
        print(f"Option 1 selected with value {args.arg2}")
    elif args.arg1 == 'option2':
        print(f"Option 2 selected with value {args.arg2}")
    else:
        print("Unknown option!")

if __name__ == "__main__":
    main()

 

2. No Usage or Help Message

import sys

def main():
    if len(sys.argv) < 3:
        print("Not enough arguments!")
        return
    
    arg1 = sys.argv[1]
    arg2 = sys.argv[2]
    
    if arg1 == 'option1':
        print(f"Option 1 selected with value {arg2}")
    elif arg1 == 'option2':
        print(f"Option 2 selected with value {arg2}")
    else:
        print("Unknown option!")

if __name__ == "__main__":
    main()


Bad Practice: Not providing a usage or help message makes it difficult for users to understand how to use the script.

Fix: Use the argparse module, which automatically provides help and usage messages.

import argparse

def main():
    parser = argparse.ArgumentParser(description="A sample argument parser.")
    parser.add_argument('arg1', type=str, help="First argument")
    parser.add_argument('arg2', type=str, help="Second argument")
    args = parser.parse_args()
    
    if args.arg1 == 'option1':
        print(f"Option 1 selected with value {args.arg2}")
    elif args.arg1 == 'option2':
        print(f"Option 2 selected with value {args.arg2}")
    else:
        print("Unknown option!")

if __name__ == "__main__":
    main()

 

No Validation of Arguments

import sys

def main():
    if len(sys.argv) < 3:
        print("Not enough arguments!")
        return
    
    arg1 = sys.argv[1]
    arg2 = sys.argv[2]
    
    if arg1 == 'option1':
        print(f"Option 1 selected with value {arg2}")
    elif arg1 == 'option2':
        print(f"Option 2 selected with value {arg2}")
    else:
        print("Unknown option!")

if __name__ == "__main__":
    main()


Bad Practice: Not validating arguments can lead to runtime errors or unexpected behavior.

Fix: Use argparse to specify the type of arguments and validate them accordingly.

import argparse

def main():
    parser = argparse.ArgumentParser(description="A sample argument parser.")
    parser.add_argument('arg1', type=str, choices=['option1', 'option2'], help="First argument")
    parser.add_argument('arg2', type=str, help="Second argument")
    args = parser.parse_args()
    
    if args.arg1 == 'option1':
        print(f"Option 1 selected with value {args.arg2}")
    elif args.arg1 == 'option2':
        print(f"Option 2 selected with value {args.arg2}")

if __name__ == "__main__":
    main()

 

Ignoring Edge Cases

import sys

def main():
    if len(sys.argv) < 3:
        print("Not enough arguments!")
        return
    
    arg1 = sys.argv[1]
    arg2 = sys.argv[2]
    
    if arg1 == 'option1':
        print(f"Option 1 selected with value {arg2}")
    elif arg1 == 'option2':
        print(f"Option 2 selected with value {arg2}")
    else:
        print("Unknown option!")

if __name__ == "__main__":
    main()


Bad Practice: Not handling edge cases like missing arguments, incorrect data types, or invalid values.

Fix: Use argparse features like default values, type checking, and required arguments to handle edge cases.

import argparse

def main():
    parser = argparse.ArgumentParser(description="A sample argument parser.")
    parser.add_argument('arg1', type=str, choices=['option1', 'option2'], help="First argument")
    parser.add_argument('arg2', type=str, help="Second argument")
    parser.add_argument('--optional', type=int, default=0, help="An optional argument")
    args = parser.parse_args()
    
    if args.arg1 == 'option1':
        print(f"Option 1 selected with value {args.arg2} and optional {args.optional}")
    elif args.arg1 == 'option2':
        print(f"Option 2 selected with value {args.arg2} and optional {args.optional}")

if __name__ == "__main__":
    main()

 

Poor Argument Naming

import sys

def main():
    if len(sys.argv) < 3:
        print("Not enough arguments!")
        return
    
    arg1 = sys.argv[1]
    arg2 = sys.argv[2]
    
    if arg1 == 'option1':
        print(f"Option 1 selected with value {arg2}")
    elif arg1 == 'option2':
        print(f"Option 2 selected with value {arg2}")
    else:
        print("Unknown option!")

if __name__ == "__main__":
    main()


Bad Practice: Using non-descriptive or ambiguous argument names can confuse users.

Fix: Use clear and descriptive argument names that convey their purpose.

import argparse

def main():
    parser = argparse.ArgumentParser(description="A sample argument parser.")
    parser.add_argument('command', type=str, choices=['start', 'stop'], help="Command to execute")
    parser.add_argument('value', type=str, help="Value associated with the command")
    args = parser.parse_args()
    
    if args.command == 'start':
        print(f"Starting with value {args.value}")
    elif args.command == 'stop':
        print(f"Stopping with value {args.value}")

if __name__ == "__main__":
    main()

 


Liên quan

Python Learning

[TIPS] Python: Compare Tuple and List

Đọc thêm
Python Learning

[Tips] Python DotDict Class

Đọc thêm
Theo dõi

Theo dõi bản tin của chúng tôi và không bao giờ bỏ lỡ những tin tức mới nhất.