Run text script. :return: True if running of commands should stop
(self, args: argparse.Namespace)
| 5476 | |
| 5477 | @with_argparser(_build_run_script_parser) |
| 5478 | def do_run_script(self, args: argparse.Namespace) -> bool | None: |
| 5479 | """Run text script. |
| 5480 | |
| 5481 | :return: True if running of commands should stop |
| 5482 | """ |
| 5483 | self.last_result = False |
| 5484 | expanded_path = os.path.abspath(os.path.expanduser(args.script_path)) |
| 5485 | |
| 5486 | # Add some protection against accidentally running a Python file. The happens when users |
| 5487 | # mix up run_script and run_pyscript. |
| 5488 | if expanded_path.endswith(".py"): |
| 5489 | self.pwarning(f"'{expanded_path}' appears to be a Python file") |
| 5490 | selection = self.select("Yes No", "Continue to try to run it as a text script? ") |
| 5491 | if selection != "Yes": |
| 5492 | return None |
| 5493 | |
| 5494 | try: |
| 5495 | # An empty file is not an error, so just return |
| 5496 | if os.path.getsize(expanded_path) == 0: |
| 5497 | self.last_result = True |
| 5498 | return None |
| 5499 | |
| 5500 | # Make sure the file is ASCII or UTF-8 encoded text |
| 5501 | if not utils.is_text_file(expanded_path): |
| 5502 | self.perror(f"'{expanded_path}' is not an ASCII or UTF-8 encoded text file") |
| 5503 | return None |
| 5504 | |
| 5505 | # Read all lines of the script |
| 5506 | with open(expanded_path, encoding="utf-8") as target: |
| 5507 | script_commands = target.read().splitlines() |
| 5508 | except OSError as ex: |
| 5509 | self.perror(f"Problem accessing script from '{expanded_path}': {ex}") |
| 5510 | return None |
| 5511 | |
| 5512 | orig_script_dir_count = len(self._script_dir) |
| 5513 | |
| 5514 | try: |
| 5515 | self._script_dir.append(os.path.dirname(expanded_path)) |
| 5516 | stop = self.runcmds_plus_hooks( |
| 5517 | script_commands, |
| 5518 | add_to_history=self.scripts_add_to_history, |
| 5519 | stop_on_keyboard_interrupt=True, |
| 5520 | ) |
| 5521 | self.last_result = True |
| 5522 | return stop |
| 5523 | finally: |
| 5524 | with self.sigint_protection: |
| 5525 | # Check if a script dir was added before an exception occurred |
| 5526 | if orig_script_dir_count != len(self._script_dir): |
| 5527 | self._script_dir.pop() |
| 5528 | |
| 5529 | @classmethod |
| 5530 | def _build__relative_run_script_parser(cls) -> Cmd2ArgumentParser: |