Python Editor

1.0.4 · maintenance · verified Fri Apr 10

python-editor is a Python library that provides a programmatic interface to the system's default text editor, usually determined by the `$EDITOR` environment variable. It allows applications to open an editor, optionally pre-fill it with content, and capture the user's input upon closing. The current version is 1.0.4, with the last release dating back to January 2019, indicating a slow or inactive release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `python-editor` to both capture user input via a temporary file and to edit an existing file. The `editor.editor()` function opens the configured editor and returns the edited content for temporary files, or saves changes directly to a specified file.

import editor
import os

def main():
    # Example 1: Open an editor to capture a commit message
    initial_text = b"# Enter your commit message above this line\n\n"
    try:
        commit_msg = editor.editor(contents=initial_text)
        if commit_msg.strip():
            print(f"Captured commit message:\n{commit_msg.decode('utf-8')}")
        else:
            print("No commit message entered.")

    except Exception as e:
        print(f"An error occurred: {e}")

    # Example 2: Open an existing file for editing
    # For demonstration, create a dummy file
    dummy_filename = 'example.txt'
    with open(dummy_filename, 'w') as f:
        f.write('This is some initial text.\n')
    
    print(f"\nOpening {dummy_filename} for editing...")
    try:
        # Note: editor.editor(filename='...') will save changes in place
        # No return value needed if editing in place
        editor.editor(filename=dummy_filename)
        print(f"Finished editing {dummy_filename}.")
        with open(dummy_filename, 'r') as f:
            print(f"Final content of {dummy_filename}:\n{f.read()}")
    except Exception as e:
        print(f"An error occurred while editing file: {e}")
    finally:
        if os.path.exists(dummy_filename):
            os.remove(dummy_filename)

if __name__ == '__main__':
    main()

view raw JSON →