From 4d761d7e8ae2cd38b1e09a05c188b5f25ee7f15e Mon Sep 17 00:00:00 2001 From: Kelly Brazil Date: Wed, 7 Sep 2022 12:52:05 -0700 Subject: [PATCH] add exception handling for file open errors --- jc/cli.py | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/jc/cli.py b/jc/cli.py index 3077513d..8a5100cc 100644 --- a/jc/cli.py +++ b/jc/cli.py @@ -434,10 +434,12 @@ def magic_parser(args): options # jc options to preserve ) + def open_text_file(path_string): with open(path_string, 'r') as f: return f.read() + def run_user_command(command): """ Use subprocess to run the user's command. Returns the STDOUT, STDERR, @@ -597,8 +599,28 @@ def main(): run_command_str = ' '.join(run_command) # older python versions if run_command_str.startswith('/proc'): - magic_found_parser = 'proc' - magic_stdout = open_text_file(run_command_str) + try: + magic_found_parser = 'proc' + magic_stdout = open_text_file(run_command_str) + + except OSError as e: + if debug: + raise + + error_msg = os.strerror(e.errno) + utils.error_message([ + f'"{run_command_str}" file could not be opened: {error_msg}.' + ]) + sys.exit(combined_exit_code(magic_exit_code, JC_ERROR_EXIT)) + + except Exception: + if debug: + raise + + utils.error_message([ + f'"{run_command_str}" file could not be opened. For details use the -d or -dd option.' + ]) + sys.exit(combined_exit_code(magic_exit_code, JC_ERROR_EXIT)) elif valid_command: try: