5

I'd like to be able to get input from the user (through raw_input() or a module) and be able to have text automatically be already entered that they can add to, delete, or modify. I know in javascript when you're using a prompt, you can do it like

var = prompt("Enter your name: ","put name here")

and it will appear as:

Enter your name:
put name here

where 'put name here' is in the text box and can be modified. I'm hoping to implement this in a shell environment (I use unix) as opposed to a window.

Any ways to do this?

Oh and tell me if I need to clarify what I am hoping for more.


I don't think you guys understand what I'm trying to do.

I basically want to include the prompt in the input, but have the user be able to backspace out the prompt/edit it if they want.

The script would possibly be used for a simple shell based one line text editor, and a tab completion type thing.

Ry-
  • 218,210
  • 55
  • 464
  • 476
Brennan Wilkes
  • 213
  • 3
  • 4
  • 13
  • 8
    This is *really difficult*. Consider saying `Enter your name [Default Name]: ` and inserting `Default Name` if the input is the empty string; that’s pretty standard for scripts. – Ry- Sep 29 '13 at 23:04
  • 1
    possible duplicate of [Python: how to modify/edit the string printed to screen and read it back?](http://stackoverflow.com/questions/7248076/python-how-to-modify-edit-the-string-printed-to-screen-and-read-it-back) – sashkello Sep 29 '13 at 23:04
  • Check out http://stackoverflow.com/questions/187621/how-to-make-a-python-command-line-program-autocomplete-arbitrary-things-not-int as well. – André Laszlo Mar 13 '14 at 12:36

2 Answers2

3

On UNIX and UNIX-alikes, such as Mac OS X and Linux, you can use the readline module. On Windows you can use pyreadline.

If you do it the way minitech suggests in his comment, write a little function to make it easier:

def input_default(prompt, default):
    return raw_input("%s [%s] " % (prompt, default)) or default

name = input_default("What is your name?", "Not Sure")
kindall
  • 178,883
  • 35
  • 278
  • 309
3

Mmm, kinda hack, but try this one.

Windows:

import win32com.client as win

shell = win.Dispatch("WScript.Shell").SendKeys("Put name here")
raw_input("Enter your name: ")

In Linux/Unix environment, you can use the pyreadline, readline or curses libraries. You can find one possible solution here:

def rlinput(prompt, prefill=''):
    readline.set_startup_hook(lambda: readline.insert_text(prefill))
    try:
        return raw_input(prompt)
    finally:
        readline.set_startup_hook()
Community
  • 1
  • 1
Yam Mesicka
  • 6,243
  • 7
  • 45
  • 64