360 Get user input via editing a temporary file in an editor. If opening the editor fails, fall
361 back to command line input
364 with tempfile.NamedTemporaryFile(mode='r+') as tmpfile:
365 if self.initial_content:
366 tmpfile.write(self.initial_content)
368 subprocess.check_call(self.editor_command_list + [tmpfile.name])
370 input_string = tmpfile.read().strip()
371 input_string = self._remove_comment_lines(input_string)
373 except (FileNotFoundError, subprocess.CalledProcessError):
374 # If editor not found or other problem with subprocess call, fall back to terminal input
375 print(f"Could not open {self.get_editor_command()}.")
376 print("Try to set your $VISUAL or $EDITOR environment variables properly.\n")
386 def _remove_comment_lines(self, a_string):
388 Remove lines from string that start with a comment character and return modified version.
390 if self.comment_string is not None:
391 a_string = "\n".join(
392 [line for line in a_string.splitlines()
393 if not line.startswith(self.comment_string)]).strip()
404 def _prompt_for_editor(self):
406 Ask user to provide editor command
408 # Prompt user for editor command until one is found which exists in PATH
410 new_editor_command_string = input("Use editor: ")
411 new_editor_command_list = shlex.split(new_editor_command_string, posix=True)
413 if shutil.which(new_editor_command_list[0]) is not None:
414 self.editor_command_list = new_editor_command_list
415 return self.editor_command_list
418 print(f"Editor '{self.editor_command_list[0]}' not found in $PATH.")