머리말
이 질문에 argparse.RawTextHelpFormatter
도움이됩니다.
이제을 사용하는 방법을 공유하고 싶습니다 argparse
.
질문과 관련이 없을 수도 있음을 알고 있습니다.
그러나 이러한 질문들은 잠시 동안 귀찮게되었습니다.
내 경험을 공유하고 싶습니다. 누군가에게 도움이되기를 바랍니다.
여기 있습니다
타사 모듈
colorama : 텍스트 색상 변경 :pip install colorama
MS Windows에서 ANSI 이스케이프 문자 시퀀스 (컬러 터미널 텍스트 및 커서 위치 지정)가 작동하도록합니다.
예
import colorama
from colorama import Fore, Back
from pathlib import Path
from os import startfile, system
SCRIPT_DIR = Path(__file__).resolve().parent
TEMPLATE_DIR = SCRIPT_DIR.joinpath('.')
def main(args):
...
if __name__ == '__main__':
colorama.init(autoreset=True)
from argparse import ArgumentParser, RawTextHelpFormatter
format_text = FormatText([(20, '<'), (60, '<')])
yellow_dc = format_text.new_dc(fore_color=Fore.YELLOW)
green_dc = format_text.new_dc(fore_color=Fore.GREEN)
red_dc = format_text.new_dc(fore_color=Fore.RED, back_color=Back.LIGHTYELLOW_EX)
script_description = \
'\n'.join([desc for desc in
[f'\n{green_dc(f"python {Path(__file__).name} [REFERENCE TEMPLATE] [OUTPUT FILE NAME]")} to create template.',
f'{green_dc(f"python {Path(__file__).name} -l *")} to get all available template',
f'{green_dc(f"python {Path(__file__).name} -o open")} open template directory so that you can put your template file there.',
# <- add your own description
]])
arg_parser = ArgumentParser(description=yellow_dc('CREATE TEMPLATE TOOL'),
# conflict_handler='resolve',
usage=script_description, formatter_class=RawTextHelpFormatter)
arg_parser.add_argument("ref", help="reference template", nargs='?')
arg_parser.add_argument("outfile", help="output file name", nargs='?')
arg_parser.add_argument("action_number", help="action number", nargs='?', type=int)
arg_parser.add_argument('--list', "-l", dest='list',
help=f"example: {green_dc('-l *')} \n"
"description: list current available template. (accept regex)")
arg_parser.add_argument('--option', "-o", dest='option',
help='\n'.join([format_text(msg_data_list) for msg_data_list in [
['example', 'description'],
[green_dc('-o open'), 'open template directory so that you can put your template file there.'],
[green_dc('-o run'), '...'],
[green_dc('-o ...'), '...'],
# <- add your own description
]]))
g_args = arg_parser.parse_args()
task_run_list = [[False, lambda: startfile('.')] if g_args.option == 'open' else None,
[False, lambda: [print(template_file_path.stem) for template_file_path in TEMPLATE_DIR.glob(f'{g_args.list}.py')]] if g_args.list else None,
# <- add your own function
]
for leave_flag, func in [task_list for task_list in task_run_list if task_list]:
func()
if leave_flag:
exit(0)
# CHECK POSITIONAL ARGUMENTS
for attr_name, value in vars(g_args).items():
if attr_name.startswith('-') or value is not None:
continue
system('cls')
print(f'error required values of {red_dc(attr_name)} is None')
print(f"if you need help, please use help command to help you: {red_dc(f'python {__file__} -h')}")
exit(-1)
main(g_args)
의 클래스 FormatText
는 다음과 같습니다
class FormatText:
__slots__ = ['align_list']
def __init__(self, align_list: list, autoreset=True):
"""
USAGE::
format_text = FormatText([(20, '<'), (60, '<')])
red_dc = format_text.new_dc(fore_color=Fore.RED)
print(red_dc(['column 1', 'column 2']))
print(red_dc('good morning'))
:param align_list:
:param autoreset:
"""
self.align_list = align_list
colorama.init(autoreset=autoreset)
def __call__(self, text_list: list):
if len(text_list) != len(self.align_list):
if isinstance(text_list, str):
return text_list
raise AttributeError
return ' '.join(f'{txt:{flag}{int_align}}' for txt, (int_align, flag) in zip(text_list, self.align_list))
def new_dc(self, fore_color: Fore = Fore.GREEN, back_color: Back = ""): # DECORATOR
"""create a device context"""
def wrap(msgs):
return back_color + fore_color + self(msgs) + Fore.RESET
return wrap