From 6407f4c5c6e669093f69aa69c61776a5f40c17b1 Mon Sep 17 00:00:00 2001 From: Kevin Van Brunt Date: Thu, 20 Dec 2018 19:18:39 -0500 Subject: Added new example script that saves help text to a file --- examples/scripts/save_help_text.py | 67 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 examples/scripts/save_help_text.py (limited to 'examples/scripts') diff --git a/examples/scripts/save_help_text.py b/examples/scripts/save_help_text.py new file mode 100644 index 00000000..31af9515 --- /dev/null +++ b/examples/scripts/save_help_text.py @@ -0,0 +1,67 @@ +# coding=utf-8 +""" +A cmd2 script that saves the help text for every command and sub-commands to a file +This is meant to be run with pyscript within a cmd2 session. +""" + +import argparse +import os +import sys +import tempfile +from typing import List + + +def get_sub_commands(parser: argparse.ArgumentParser) -> List[str]: + """Returns a list of sub-commands for an ArgumentParser""" + + sub_cmds = [] + + # Check if this is parser has sub-commands + if parser is not None and parser._subparsers is not None: + + # Find the _SubParsersAction for the sub-commands of this parser + for action in parser._subparsers._actions: + if isinstance(action, argparse._SubParsersAction): + for sub_cmd, sub_cmd_parser in action.choices.items(): + sub_cmds.append(sub_cmd) + + # Look for nested sub-commands + for nested_sub_cmd in get_sub_commands(sub_cmd_parser): + sub_cmds.append('{} {}'.format(sub_cmd, nested_sub_cmd)) + + break + + return sub_cmds + + +# Make sure we have access to self +if 'self' not in globals(): + print("Run 'set locals_in_py true' and then rerun this script") + +# Make sure the user passed in an output file +elif len(sys.argv) != 2: + print("Usage: {} ".format(os.path.basename(sys.argv[0]))) +else: + outfile = sys.argv[1] + + # Get a list of all commands and help topics and then filter out duplicates + to_print = set(self.get_all_commands()) | set(self.get_help_topics()) + + # Create a script that will call help on each command and topic and write its output to a file + with tempfile.NamedTemporaryFile(mode='w+t', delete=False) as temp: + + # First delete any existing output file + temp.write('!rm -f {}\n'.format(outfile)) + + for item in to_print: + temp.write('help {} >> {}\n'.format(item, outfile)) + + # Add any sub-commands + for subcmd in get_sub_commands(getattr(self.cmd_func(item), 'argparser', None)): + temp.write('help {} {} >> {}\n'.format(item, subcmd, outfile)) + + # Have the script delete itself as its last step + temp.write('!rm -f {}\n'.format(temp.name)) + + # Tell cmd2 to run the script as its next command + self.cmdqueue.insert(0, "load '{}'".format(temp.name)) -- cgit v1.2.1 From 20dec6d0b9c8cf872da932fdd8a73ea1c80172fe Mon Sep 17 00:00:00 2001 From: Kevin Van Brunt Date: Thu, 20 Dec 2018 19:38:35 -0500 Subject: Fixing flake8 warning --- examples/scripts/save_help_text.py | 1 + 1 file changed, 1 insertion(+) (limited to 'examples/scripts') diff --git a/examples/scripts/save_help_text.py b/examples/scripts/save_help_text.py index 31af9515..8c3dc9e7 100644 --- a/examples/scripts/save_help_text.py +++ b/examples/scripts/save_help_text.py @@ -1,4 +1,5 @@ # coding=utf-8 +# flake8: noqa F821 """ A cmd2 script that saves the help text for every command and sub-commands to a file This is meant to be run with pyscript within a cmd2 session. -- cgit v1.2.1 From 7b6db96da6aae4ff0124f47b9cb9b04c9f33cb98 Mon Sep 17 00:00:00 2001 From: Kevin Van Brunt Date: Thu, 20 Dec 2018 19:53:53 -0500 Subject: Added labels for each command help text --- examples/scripts/save_help_text.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) (limited to 'examples/scripts') diff --git a/examples/scripts/save_help_text.py b/examples/scripts/save_help_text.py index 8c3dc9e7..2aa18b84 100644 --- a/examples/scripts/save_help_text.py +++ b/examples/scripts/save_help_text.py @@ -11,6 +11,8 @@ import sys import tempfile from typing import List +ASTERISKS = "********************************************************" + def get_sub_commands(parser: argparse.ArgumentParser) -> List[str]: """Returns a list of sub-commands for an ArgumentParser""" @@ -43,7 +45,7 @@ if 'self' not in globals(): elif len(sys.argv) != 2: print("Usage: {} ".format(os.path.basename(sys.argv[0]))) else: - outfile = sys.argv[1] + outfile = os.path.expanduser(sys.argv[1]) # Get a list of all commands and help topics and then filter out duplicates to_print = set(self.get_all_commands()) | set(self.get_help_topics()) @@ -55,11 +57,20 @@ else: temp.write('!rm -f {}\n'.format(outfile)) for item in to_print: + header = '{}\\nCOMMAND: {}\\n{}\\n'.format(ASTERISKS, item, ASTERISKS) + temp.write('py print("{}") >> {}\n'.format(header, outfile)) temp.write('help {} >> {}\n'.format(item, outfile)) # Add any sub-commands for subcmd in get_sub_commands(getattr(self.cmd_func(item), 'argparser', None)): - temp.write('help {} {} >> {}\n'.format(item, subcmd, outfile)) + full_cmd = '{} {}'.format(item, subcmd) + header = '{}\\nCOMMAND: {}\\n{}\\n'.format(ASTERISKS, full_cmd, ASTERISKS) + + temp.write('py print("{}") >> {}\n'.format(header, outfile)) + temp.write('help {} >> {}\n'.format(full_cmd, outfile)) + + # Inform the user where output was written + temp.write('py print("Output written to {}")\n'.format(outfile)) # Have the script delete itself as its last step temp.write('!rm -f {}\n'.format(temp.name)) -- cgit v1.2.1 From 068e83fb9bbabd74313f3c245217343ed015fe86 Mon Sep 17 00:00:00 2001 From: Kevin Van Brunt Date: Thu, 20 Dec 2018 21:16:19 -0500 Subject: Refactored script and made OS independent by removing rm calls --- examples/scripts/save_help_text.py | 66 +++++++++++++++++++++++--------------- 1 file changed, 40 insertions(+), 26 deletions(-) (limited to 'examples/scripts') diff --git a/examples/scripts/save_help_text.py b/examples/scripts/save_help_text.py index 2aa18b84..709edfca 100644 --- a/examples/scripts/save_help_text.py +++ b/examples/scripts/save_help_text.py @@ -9,14 +9,13 @@ import argparse import os import sys import tempfile -from typing import List +from typing import List, TextIO ASTERISKS = "********************************************************" def get_sub_commands(parser: argparse.ArgumentParser) -> List[str]: - """Returns a list of sub-commands for an ArgumentParser""" - + """Get a list of sub-commands for an ArgumentParser""" sub_cmds = [] # Check if this is parser has sub-commands @@ -37,43 +36,58 @@ def get_sub_commands(parser: argparse.ArgumentParser) -> List[str]: return sub_cmds -# Make sure we have access to self -if 'self' not in globals(): - print("Run 'set locals_in_py true' and then rerun this script") +def add_command_to_script(command: str, temp_file: TextIO, outfile_path: str) -> None: + """ + Write to the script the commands necessary to write both a + header and help text for a command to the output file + """ + header = '{}\\nCOMMAND: {}\\n{}\\n'.format(ASTERISKS, command, ASTERISKS) + temp_file.write('py print("{}") >> {}\n'.format(header, outfile_path)) + temp_file.write('help {} >> {}\n'.format(command, outfile_path)) -# Make sure the user passed in an output file -elif len(sys.argv) != 2: - print("Usage: {} ".format(os.path.basename(sys.argv[0]))) -else: - outfile = os.path.expanduser(sys.argv[1]) - # Get a list of all commands and help topics and then filter out duplicates - to_print = set(self.get_all_commands()) | set(self.get_help_topics()) +def main(): + """Main function of this script""" + + # Make sure we have access to self + if 'self' not in globals(): + print("Run 'set locals_in_py true' and then rerun this script") + return + + # Make sure the user passed in an output file + if len(sys.argv) != 2: + print("Usage: {} ".format(os.path.basename(sys.argv[0]))) + return + + # Get output file path + outfile = os.path.expanduser(sys.argv[1]) # Create a script that will call help on each command and topic and write its output to a file - with tempfile.NamedTemporaryFile(mode='w+t', delete=False) as temp: + with tempfile.NamedTemporaryFile(mode='w+t', delete=False) as temp_file: # First delete any existing output file - temp.write('!rm -f {}\n'.format(outfile)) + temp_file.write('py if os.path.exists("{0}"): os.remove("{0}")\n'.format(outfile)) + + # Get a list of all commands and help topics and then filter out duplicates + to_save = set(self.get_all_commands()) | set(self.get_help_topics()) - for item in to_print: - header = '{}\\nCOMMAND: {}\\n{}\\n'.format(ASTERISKS, item, ASTERISKS) - temp.write('py print("{}") >> {}\n'.format(header, outfile)) - temp.write('help {} >> {}\n'.format(item, outfile)) + for item in to_save: + add_command_to_script(item, temp_file, outfile) # Add any sub-commands for subcmd in get_sub_commands(getattr(self.cmd_func(item), 'argparser', None)): full_cmd = '{} {}'.format(item, subcmd) - header = '{}\\nCOMMAND: {}\\n{}\\n'.format(ASTERISKS, full_cmd, ASTERISKS) - - temp.write('py print("{}") >> {}\n'.format(header, outfile)) - temp.write('help {} >> {}\n'.format(full_cmd, outfile)) + add_command_to_script(full_cmd, temp_file, outfile) # Inform the user where output was written - temp.write('py print("Output written to {}")\n'.format(outfile)) + temp_file.write('py print("Output written to {}")\n'.format(outfile)) # Have the script delete itself as its last step - temp.write('!rm -f {}\n'.format(temp.name)) + temp_file.write('py os.remove("{}")\n'.format(temp_file.name)) # Tell cmd2 to run the script as its next command - self.cmdqueue.insert(0, "load '{}'".format(temp.name)) + self.cmdqueue.insert(0, 'load "{}"'.format(temp_file.name)) + + +# Run main function +main() -- cgit v1.2.1 From 8bb92a8ad40a253070a68b2126afc2ef66fa9a4f Mon Sep 17 00:00:00 2001 From: Kevin Van Brunt Date: Thu, 20 Dec 2018 21:20:07 -0500 Subject: Updated documentation --- examples/scripts/save_help_text.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'examples/scripts') diff --git a/examples/scripts/save_help_text.py b/examples/scripts/save_help_text.py index 709edfca..9bdc1efa 100644 --- a/examples/scripts/save_help_text.py +++ b/examples/scripts/save_help_text.py @@ -1,8 +1,8 @@ # coding=utf-8 # flake8: noqa F821 """ -A cmd2 script that saves the help text for every command and sub-commands to a file -This is meant to be run with pyscript within a cmd2 session. +A cmd2 script that saves the help text for every command and sub-command to a file. +This is meant to be run within a cmd2 session using pyscript. """ import argparse -- cgit v1.2.1 From 25c8d65bc6f885cc2620c554f7211f7b566ad2ac Mon Sep 17 00:00:00 2001 From: Kevin Van Brunt Date: Fri, 21 Dec 2018 00:20:16 -0500 Subject: Refactored script to use app() --- examples/scripts/save_help_text.py | 59 +++++++++++++++++--------------------- 1 file changed, 27 insertions(+), 32 deletions(-) (limited to 'examples/scripts') diff --git a/examples/scripts/save_help_text.py b/examples/scripts/save_help_text.py index 9bdc1efa..d08463f2 100644 --- a/examples/scripts/save_help_text.py +++ b/examples/scripts/save_help_text.py @@ -8,7 +8,6 @@ This is meant to be run within a cmd2 session using pyscript. import argparse import os import sys -import tempfile from typing import List, TextIO ASTERISKS = "********************************************************" @@ -33,20 +32,22 @@ def get_sub_commands(parser: argparse.ArgumentParser) -> List[str]: break + sub_cmds.sort() return sub_cmds -def add_command_to_script(command: str, temp_file: TextIO, outfile_path: str) -> None: +def add_help_to_file(command: str, outfile: TextIO) -> None: """ - Write to the script the commands necessary to write both a - header and help text for a command to the output file + Write a header and help text for a command to the output file """ - header = '{}\\nCOMMAND: {}\\n{}\\n'.format(ASTERISKS, command, ASTERISKS) - temp_file.write('py print("{}") >> {}\n'.format(header, outfile_path)) - temp_file.write('help {} >> {}\n'.format(command, outfile_path)) + header = '{}\nCOMMAND: {}\n{}\n'.format(ASTERISKS, command, ASTERISKS) + outfile.write(header) + result = app('help {}'.format(command)) + outfile.write(result.stdout) -def main(): + +def main() -> None: """Main function of this script""" # Make sure we have access to self @@ -59,34 +60,28 @@ def main(): print("Usage: {} ".format(os.path.basename(sys.argv[0]))) return - # Get output file path - outfile = os.path.expanduser(sys.argv[1]) - - # Create a script that will call help on each command and topic and write its output to a file - with tempfile.NamedTemporaryFile(mode='w+t', delete=False) as temp_file: - - # First delete any existing output file - temp_file.write('py if os.path.exists("{0}"): os.remove("{0}")\n'.format(outfile)) - - # Get a list of all commands and help topics and then filter out duplicates - to_save = set(self.get_all_commands()) | set(self.get_help_topics()) - - for item in to_save: - add_command_to_script(item, temp_file, outfile) + # Open the output file + outfile_path = os.path.expanduser(sys.argv[1]) + try: + outfile = open(outfile_path, 'w') + except OSError as e: + print("Error opening {} because: {}".format(outfile_path, e)) + return - # Add any sub-commands - for subcmd in get_sub_commands(getattr(self.cmd_func(item), 'argparser', None)): - full_cmd = '{} {}'.format(item, subcmd) - add_command_to_script(full_cmd, temp_file, outfile) + # Get a list of all commands and help topics and then filter out duplicates + to_save = list(set(self.get_all_commands()) | set(self.get_help_topics())) + to_save.sort() - # Inform the user where output was written - temp_file.write('py print("Output written to {}")\n'.format(outfile)) + for item in to_save: + add_help_to_file(item, outfile) - # Have the script delete itself as its last step - temp_file.write('py os.remove("{}")\n'.format(temp_file.name)) + # Add any sub-commands + for subcmd in get_sub_commands(getattr(self.cmd_func(item), 'argparser', None)): + full_cmd = '{} {}'.format(item, subcmd) + add_help_to_file(full_cmd, outfile) - # Tell cmd2 to run the script as its next command - self.cmdqueue.insert(0, 'load "{}"'.format(temp_file.name)) + outfile.close() + print("Output written to {}".format(outfile_path)) # Run main function -- cgit v1.2.1 From 465bec70ac5e21fca481b31d5d041fc4b57ca1de Mon Sep 17 00:00:00 2001 From: Kevin Van Brunt Date: Fri, 21 Dec 2018 00:24:45 -0500 Subject: Removed newlines --- examples/scripts/save_help_text.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'examples/scripts') diff --git a/examples/scripts/save_help_text.py b/examples/scripts/save_help_text.py index d08463f2..d3c8a91e 100644 --- a/examples/scripts/save_help_text.py +++ b/examples/scripts/save_help_text.py @@ -37,9 +37,7 @@ def get_sub_commands(parser: argparse.ArgumentParser) -> List[str]: def add_help_to_file(command: str, outfile: TextIO) -> None: - """ - Write a header and help text for a command to the output file - """ + """Write a header and help text for a command to the output file""" header = '{}\nCOMMAND: {}\n{}\n'.format(ASTERISKS, command, ASTERISKS) outfile.write(header) -- cgit v1.2.1