用于在CLI中编辑文本的Python模块
有没有什么Python模块或者命令,可以让我让我的Python程序进入一个命令行文本编辑器,先把一些文本填进去,然后在退出时把这些文本取出来放到一个变量里呢?
现在我让用户用raw_input()输入内容,但我想要一个更强大的方法,并且能在命令行上显示出来。
4 个回答
1
这是我为另一个项目写的一个函数。它允许用户编辑一行文本,支持换行和光标移动,你可以用箭头键在文本中前后移动。这个功能依赖于一个叫做 readchar 的模块,你可以通过 pip3 install readchar
来安装它,这样它应该能在Windows上运行,不过我只在Linux终端和initramfs中测试过。
GitHub链接: https://github.com/SurpriseDog/KeyLocker/blob/main/text_editor.py
(这个链接可能会更及时更新)
#!/usr/bin/python3
import sys
import shutil
from readchar import readkey
def text_editor(init='', prompt=''):
'''
Allow user to edit a line of text complete with support for line wraps
and a cursor | you can move back and forth with the arrow keys.
init = initial text supplied to edit
prompt = Decoration presented before the text (not editable and not returned)
'''
term_width = shutil.get_terminal_size()[0]
ptr = len(init)
text = list(init)
prompt = list(prompt)
c = 0
while True:
if ptr and ptr > len(text):
ptr = len(text)
copy = prompt + text.copy()
if ptr < len(text):
copy.insert(ptr + len(prompt), '|')
# Line wraps support:
if len(copy) > term_width:
cut = len(copy) + 3 - term_width
if ptr > len(copy) / 2:
copy = ['<'] * 3 + copy[cut:]
else:
copy = copy[:-cut] + ['>'] * 3
# Display current line
print('\r' * term_width + ''.join(copy), end=' ' * (term_width - len(copy)))
# Read new character into c
if c in (53, 54):
# Page up/down bug
c = readkey()
if c == '~':
continue
else:
c = readkey()
if len(c) > 1:
# Control Character
c = ord(c[-1])
if c == 68: # Left
ptr -= 1
elif c == 67: # Right
ptr += 1
elif c == 53: # PgDn
ptr -= term_width // 2
elif c == 54: # PgUp
ptr += term_width // 2
elif c == 70: # End
ptr = len(text)
elif c == 72: # Home
ptr = 0
else:
print("\nUnknown control character:", c)
print("Press ctrl-c to quit.")
continue
if ptr < 0:
ptr = 0
if ptr > len(text):
ptr = len(text)
else:
num = ord(c)
if num in (13, 10): # Enter
print()
return ''.join(text)
elif num == 127: # Backspace
if text:
text.pop(ptr - 1)
ptr -= 1
elif num == 3: # Ctrl-C
sys.exit(1)
else:
# Insert normal character into text.
text.insert(ptr, c)
ptr += 1
if __name__ == "__main__":
print("Result =", text_editor('Edit this text', prompt="Prompt: "))
9
好吧,你可以通过一个叫做子进程的东西来启动用户的 $EDITOR(编辑器),并且可以编辑一个临时文件:
import tempfile
import subprocess
import os
t = tempfile.NamedTemporaryFile(delete=False)
try:
editor = os.environ['EDITOR']
except KeyError:
editor = 'nano'
subprocess.call([editor, t.name])
2
你可以看看 urwid,这是一个基于curses的完整Python用户界面工具包。它让你可以设计非常复杂的界面,并且包含了不同类型的编辑框,适用于不同类型的文本。