or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-python-editor

Programmatically open an editor, capture the result.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/python-editor@1.0.x

To install, run

npx @tessl/cli install tessl/pypi-python-editor@1.0.0

0

# Python Editor

1

2

A Python library for programmatically interfacing with system text editors. The editor module provides a simple API that allows developers to open text editors in subprocesses, capture user input, and handle the results with automatic editor detection and cross-platform compatibility.

3

4

## Package Information

5

6

- **Package Name**: python-editor

7

- **Package Type**: pypi

8

- **Language**: Python

9

- **Installation**: `pip install python-editor`

10

11

## Core Imports

12

13

```python

14

import editor

15

```

16

17

## Basic Usage

18

19

```python

20

import editor

21

22

# Open editor with initial content

23

commit_msg = editor.edit(contents=b"# Enter commit message here")

24

print(commit_msg.decode())

25

26

# Edit an existing file

27

editor.edit(filename="README.txt")

28

29

# Use TTY for piped programs

30

editor.edit(contents=b"Initial content", use_tty=True)

31

32

# Create temporary file with specific suffix

33

content = editor.edit(contents=b"# Comments", suffix='.py')

34

```

35

36

## Architecture

37

38

The library follows a simple three-stage process:

39

40

1. **Editor Detection**: Finds the appropriate editor using environment variables (`$VISUAL`, `$EDITOR`) or system defaults (`editor`, `vim`, `emacs`, `nano`)

41

2. **File Preparation**: Creates temporary files when needed and pre-populates content

42

3. **Subprocess Invocation**: Launches the editor with platform-appropriate arguments and handles TTY redirection for piped programs

43

44

The design prioritizes simplicity and cross-platform compatibility, automatically handling editor-specific command-line arguments and TTY management.

45

46

## Capabilities

47

48

### Text Editor Invocation

49

50

The primary functionality for opening text editors and capturing results.

51

52

```python { .api }

53

def edit(filename=None, contents=None, use_tty=None, suffix=''):

54

"""

55

Open a text editor and capture the result.

56

57

Parameters:

58

- filename (str, optional): Path to file to edit. If None, creates temporary file

59

- contents (bytes/str, optional): Initial contents to populate in editor

60

- use_tty (bool, optional): Whether to use TTY for output. Auto-detected if None

61

- suffix (str, optional): File suffix for temporary files when filename is None

62

63

Returns:

64

bytes: Contents of the file after editing

65

66

Raises:

67

EditorError: If no viable editor can be found on the system

68

"""

69

```

70

71

### Editor Detection

72

73

Discovers the preferred text editor from environment variables or system defaults.

74

75

```python { .api }

76

def get_editor():

77

"""

78

Get the preferred editor from environment or system defaults.

79

80

Returns:

81

str: Path to editor executable

82

83

Raises:

84

EditorError: If no viable editor can be found on the system

85

"""

86

```

87

88

### Utility Functions

89

90

Advanced utility functions for customizing editor behavior.

91

92

```python { .api }

93

def get_default_editors():

94

"""

95

Get the list of default editors to search for.

96

97

Returns:

98

list: List of editor names in priority order ['editor', 'vim', 'emacs', 'nano']

99

"""

100

101

def get_editor_args(editor):

102

"""

103

Get command-line arguments for specific editors.

104

105

Parameters:

106

- editor (str): Editor name or path

107

108

Returns:

109

list: List of command-line arguments appropriate for the editor

110

"""

111

```

112

113

### Module Constants

114

115

```python { .api }

116

__version__: str

117

# Version string of the python-editor package

118

119

__all__: list

120

# Exported API: ['edit', 'get_editor', 'EditorError']

121

```

122

123

## Error Handling

124

125

```python { .api }

126

class EditorError(RuntimeError):

127

"""

128

Exception raised when editor operations fail.

129

130

Typically raised when no viable editor can be found on the system.

131

"""

132

```

133

134

## Editor Detection Logic

135

136

The library uses the following priority order to find an editor:

137

138

1. **Environment Variables**: Checks `$VISUAL` then `$EDITOR`

139

2. **System Defaults**: Searches for common editors in PATH:

140

- `editor` (system default)

141

- `vim`

142

- `emacs`

143

- `nano`

144

145

## Platform Support

146

147

- **Cross-platform**: Works on Windows, macOS, and Linux

148

- **TTY Handling**:

149

- Windows uses `CON:` for TTY

150

- Unix/Linux uses `/dev/tty`

151

- **Editor-specific Arguments**: Automatically applies appropriate command-line arguments:

152

- `vim/gvim`: `-f -o` (foreground, open in tabs)

153

- `emacs`: `-nw` (no window system)

154

- `gedit`: `-w --new-window` (wait, new window)

155

- `nano`: `-R` (restricted mode)

156

157

## Usage Examples

158

159

### Basic Text Editing

160

161

```python

162

import editor

163

164

# Simple text editing

165

content = editor.edit(contents="Initial text")

166

print("Edited content:", content.decode())

167

```

168

169

### File Editing

170

171

```python

172

import editor

173

174

# Edit existing file in place

175

editor.edit(filename="/path/to/file.txt")

176

177

# Edit file with initial content (overwrites existing)

178

editor.edit(filename="/path/to/file.txt", contents="New content")

179

```

180

181

### Temporary File Creation

182

183

```python

184

import editor

185

186

# Create temporary Python file

187

code = editor.edit(suffix='.py', contents='# Write your Python code here')

188

print("Python code:", code.decode())

189

190

# Create temporary file with no initial content

191

notes = editor.edit(suffix='.md')

192

print("Notes:", notes.decode())

193

```

194

195

### TTY Usage for Piped Programs

196

197

```python

198

import editor

199

200

# When stdout is piped, use TTY for interactive editing

201

content = editor.edit(contents="Edit this text", use_tty=True)

202

```

203

204

### Advanced Usage

205

206

```python

207

import editor

208

209

# Check available default editors

210

default_editors = editor.get_default_editors()

211

print("Default editors:", default_editors)

212

213

# Get editor-specific arguments

214

vim_args = editor.get_editor_args('vim')

215

print("Vim arguments:", vim_args) # ['-f', '-o']

216

217

# Check version

218

print("Library version:", editor.__version__)

219

```

220

221

### Error Handling

222

223

```python

224

import editor

225

226

try:

227

content = editor.edit(contents="Some text")

228

print("Success:", content.decode())

229

except editor.EditorError as e:

230

print("Editor error:", e)

231

print("Please set your $EDITOR environment variable")

232

```