开发者

Crossplatform method for inserting text into raw_input (to avoid readine) in Python

开发者 https://www.devze.com 2023-01-09 05:55 出处:网络
I have an application (CLI) which includes the feature of editing account information. It does this by asking a question and putting in the old value in the answer so that it is editable. Currently I\

I have an application (CLI) which includes the feature of editing account information. It does this by asking a question and putting in the old value in the answer so that it is editable. Currently I'm using the readline module to do this. I'd like another way of doing the same thing that avoids this module (I want to allow the app to run with all features on Windows as well as GNU/Linux any operating system that python runs on).

I originally found the following code (I modified it a bit to fit into a function) at the following website but since that thread is 4 years old I figured I'd ask here. http://bytes.com/topic/python/answers/471407-default-editable-string-raw_input

import readline
def editInput(question, old_value):
    readline.set_startup_hook(lambda: readline.insert_text(old_value))
    try:
        new_value = raw_input(question)
    finally:
        readline.set_startup_hook(None)
    return new_value

editInput('What\'s the answer? ', '32')

UPDATE: I don't necessarily need an alternative for 开发者_如何转开发readline (such as PyReadline). I just need the same result. I updated the question to mention that I don't necessarily need it to run on Windows and GNU/Linux but on any OS supported by python. So basically, only use very basic functions (such as sys.stdin, etc.)


Line editing functionality is far from trivial to duplicate. For example, just a functionality such as "read the next keystroke without echoing" (even before you start intepreting the meaning of that keystroke in order to reposition the cursor and alter the on-screen appearance as well as the remembered contents of the text line being edited) cannot be done simply in a cross-platform way: you need msvcrt functionality on Windows and curses functionality on Unix-y systems -- and your demand that it works on any OS supported by Python looms huge, and impossible to satisfy.

You need to delimit very strictly the set of operating systems / platforms on which it must run, and the subset of line editing functionality it must absolutely provide, before an answer can be considered. If you just can't delimit those sets, then the answer is easy: what you're asking for is, in its excessive generality, simply impossible.


Why not use PyReadline? It is used by IPython for more or less the same functionality and is well supported by them.

Actually, scratch that. I have just tried it and it doesn't work. Likely, pyreadline doesn't support set_startup_hook.

0

精彩评论

暂无评论...
验证码 换一张
取 消