Skip to content

Instantly share code, notes, and snippets.

@LordShedy
Last active August 7, 2021 22:42
Show Gist options
  • Select an option

  • Save LordShedy/a10104d957959059f78cd34da94b2402 to your computer and use it in GitHub Desktop.

Select an option

Save LordShedy/a10104d957959059f78cd34da94b2402 to your computer and use it in GitHub Desktop.
I like using the funcion of var_dump to debug my python code but after the debuggement is over I am too lazy to delete the lines containing var_dump, this script I wrote does it for you.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import sys
import logging
import re
LOGGER = logging.getLogger()
LOGGER_SEVERITY = logging.DEBUG
LOGGER_MESSAGE_FORMAT = r'%(asctime)s %(levelname)-8s %(message)s'
def setup_logger():
# type: () -> None
"""Function for setting up global logger parameters.
"""
logging.basicConfig(level=LOGGER_SEVERITY, format=LOGGER_MESSAGE_FORMAT)
def parse_cmd():
# type: () -> argparse.Namespace
"""Function for parsing command line arguments.
Returns:
argparse.Namespace: Parsed command line arguments.
"""
parser = argparse.ArgumentParser(description=(
'Scrip that removes all var_dump lines from a python script.'
))
parser.add_argument('file', help="Filepath of the script to var_dumper")
return parser.parse_args()
def write_file(file_name, content):
# type: (str, str) -> bool
"""Function to write content into a file.
Args:
file_name (str): Name of the file to be appended/written.
content (str): The content to be written.
Returns:
bool: True if successfully written.
"""
try:
with open(file_name, 'w') as opened_file:
opened_file.write(content)
except IOError:
sys.exit("There was error while reading or writing to the file.")
return True
def read_file_split_lines(data_file_path):
# type: (str) -> list
"""
Function to read a file and return list of its lines.
Args:
data_file_path (str): Path of a file to read.
Returns:
list: List of read lines.
"""
try:
opened_file = open(data_file_path, "r")
except IOError:
sys.exit("There was error while loading the file.")
else:
try:
data_file_content = opened_file.read().splitlines()
return data_file_content
except IOError:
sys.exit(data_file_path + " is not a valid file!")
def list_to_string(input_list):
# type: (list) -> str
# return string
return "\n".join(input_list)
def main(args):
# type: (argparse.Namespace) -> int
return_code: int = 0
# setup logger parameters
setup_logger()
source_file = args.file
source_file_lines = read_file_split_lines(source_file)
# create empty list of strings (updated output goes here)
updated_file_lines: list[str] = []
LOGGER.info("Searching for var_dump lines within \"%s\" file.",
source_file)
var_dump_lines_count: int = 0
for source_file_line in source_file_lines:
regex = r'(^from var_dump\([^\n]+|^\s+var_dump[^\n]+)'
match = re.search(regex, source_file_line, re.M)
if match is None:
updated_file_lines.append(source_file_line)
else:
var_dump_lines_count += 1
LOGGER.info("Located a line with var_dump, removing the line.")
if var_dump_lines_count == 0:
LOGGER.info("No lines with var_dump were located, nothing was done.")
else:
LOGGER.info(
"%s lines with var_dump was located and removed from the script.",
var_dump_lines_count)
updated_file_content = list_to_string(updated_file_lines)
if write_file(source_file, updated_file_content) is not True:
return_code = 2
return return_code
if __name__ == "__main__":
try:
ARGS = parse_cmd()
EXIT_CODE = main(ARGS)
except Exception as exc: # noqa
LOGGER.critical(
"An unexpected error occurred during running script: %s", exc)
EXIT_CODE = 99
else:
if EXIT_CODE:
LOGGER.warning("The script was finished with error(s).")
else:
LOGGER.info("The script was finished without an error.")
sys.exit(EXIT_CODE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment