Open the default text editor
The 'editor' library provides a programmatic interface to open the system's default text editor from within Python scripts. It allows editing new content, existing files, or temporary files, and returns the modified content. Currently at version 1.7.0, the library is actively maintained with frequent patch releases, primarily for dependency updates and minor improvements.
Warnings
- gotcha When providing initial content to the editor (via the `contents` argument), it must be a `bytes` object, not a `str`, in Python 3. Passing a string will result in a `TypeError`.
- gotcha The specific editor launched by the library is determined by the `VISUAL` or `EDITOR` environment variables, in that order. If neither is set, it defaults to 'Notepad' on Windows and 'vim' on other operating systems. This can lead to unexpected editors opening if the environment variables are not explicitly configured.
- gotcha The `editor.edit()` (or `editor.editor()`) function is blocking. It will pause the execution of your Python script until the user closes the external text editor. This behavior is by design, but developers should be aware that their application will halt during the editing session.
- gotcha If no `file` argument is provided to `editor.edit()`, the library creates a temporary file. The content is written to this temporary file for editing, and once the editor is closed, the modified content is returned, and the temporary file is automatically deleted. Changes made are not persistently saved to disk unless an explicit `file` path is provided.
Install
-
pip install editor
Imports
- editor
import editor
Quickstart
import editor
import os
# Example 1: Edit new content in a temporary file
# The content must be a bytes object for Python 3.
initial_content = b"# Enter your commit message here\n\n"
commit_message = editor.edit(contents=initial_content)
print(f"User entered: {commit_message.decode('utf-8')}")
# Example 2: Edit an existing file (or create a new one)
# Ensure a dummy file exists for the example
file_path = "my_document.txt"
with open(file_path, "w") as f:
f.write("Hello, World!\nThis is a test file.\n")
edited_content = editor.edit(file=file_path)
print(f"Content of {file_path} after editing: {edited_content.decode('utf-8')}")
# Clean up the dummy file
os.remove(file_path)