Show default value for editing on Python input pos

2019-01-01 13:19发布

Is it possible for python to accept input like this:

Folder name: Download

But instead of the user typing "Download" it is already there as a initial value. If the user wants to edit it as "Downloads" all he has to do is add a 's' and press enter.

Using normal input command:

folder=input('Folder name: ')

all I can get is a blank prompt:

Folder name:

Is there a simple way to do this that I'm missing?

标签: python input
11条回答
怪性笑人.
2楼-- · 2019-01-01 13:47

The standard library functions input() and raw_input() don't have this functionality. If you're using Linux you can use the readline module to define an input function that uses a prefill value and advanced line editing:

def rlinput(prompt, prefill=''):
   readline.set_startup_hook(lambda: readline.insert_text(prefill))
   try:
      return raw_input(prompt)
   finally:
      readline.set_startup_hook()
查看更多
闭嘴吧你
3楼-- · 2019-01-01 13:50

If you do that, the user would have to delete the existing word. What about providing a default value if the user hits "return"?

>>> default_folder = "My Documents"
>>> try: folder = input("folder name [%s]:" %default_folder)
... except SyntaxError: folder = default_folder
查看更多
浅入江南
4楼-- · 2019-01-01 13:58

I think that the best (the easiest and most portable) solution is a combination of @rlotun and @Stephen answers:

default = '/default/path/'
dir = raw_input('Folder [%s]' % default)
dir = dir or default
查看更多
与君花间醉酒
5楼-- · 2019-01-01 14:00

I finally found a simple alternative that works on Windows and Linux. Essentially, i'm using the pyautogui module to simulate the user's input. in praxis, that looks like this:

from pyautogui import typewrite

print("enter folder name: ")
typewrite("Default Value")
folder = input()

Example

A Word of Warning:

  1. Theoretically, the user can insert characters in the middle of the "default" input by pressing a key before typewrite finishes.
  2. pyautogui is notoriously unreliable on headless systems, so make sure to provide a backup solution in case the import fails. If you run into No module named 'Xlib', try to install the python3-xlib or python-xlib package (or the xlib module). Running over ssh can also be a problem.

An example fallback implementation:

Since a missing x-server can logically only happen on linux, here's an implementation that uses sth's answer as fallback:

try:
    from pyautogui import typewrite
    autogui = True
except (ImportError, KeyError):
    import readline
    autogui = False

def rlinput(prompt, prefill=''):
    if autogui:
        print(prompt)
        typewrite(prefill)
        return input()
    else:
        readline.set_startup_hook(lambda: readline.insert_text(prefill))
        try:
            return input(prompt)
        finally:
            readline.set_startup_hook()
查看更多
心情的温度
6楼-- · 2019-01-01 14:01

This works in windows.

import win32console

_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)

def input_def(prompt, default=''):
    keys = []
    for c in unicode(default):
        evt = win32console.PyINPUT_RECORDType(win32console.KEY_EVENT)
        evt.Char = c
        evt.RepeatCount = 1
        evt.KeyDown = True
        keys.append(evt)

    _stdin.WriteConsoleInput(keys)
    return raw_input(prompt)

if __name__ == '__main__':
    name = input_def('Folder name: ')
    print
    print name
查看更多
初与友歌
7楼-- · 2019-01-01 14:01

Not the best aproach but for the sake of sharing... You could use Javascript to get all sort of inputs in IPython Notebook.

from IPython.display import HTML
newvar = ""
htm = """
<input id="inptval" style="width:60%;" type="text" value="This is an editable default value.">
<button onclick="set_value()" style="width:20%;">OK</button>

<script type="text/Javascript">
    function set_value(){
        var input_value = document.getElementById('inptval').value;
        var command = "newvar = '" + input_value + "'";
        var kernel = IPython.notebook.kernel;
        kernel.execute(command);
    }
</script>
"""
HTML(htm)

On the next cell you can use the new variable:

print newvar
查看更多
登录 后发表回答