Python模块用于在CLI中编辑文本

4

有没有一些Python模块或命令可以让我的Python程序进入CLI文本编辑器,填充编辑器的内容,并在退出时将文本导出到某个变量中?

目前我让用户使用raw_input()输入内容,但我希望有比这更强大的方式,并且可以在CLI上显示它。

4个回答

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的完整UI工具包,适用于Python。它允许您定义非常复杂的接口,并包括不同的编辑框类型以处理不同类型的文本。

很遗憾,目前它不适用于Windows。即使您安装了Windows curses框架。 - ProfVersaggi

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: "))

我想要一个类似的图书馆,但支持多行文本。你知道有吗? - undefined

0
如果您不需要Windows支持,可以使用readline模块来获取基本的命令行编辑功能,就像在shell提示符下一样。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接