2

I've got a script that pulls text from a Web server. I want to give the user (me) an opportunity to edit that text so they can select which part to keep. Ideally, it would be something like this:

editedText= raw_input(defaultText)

So, defaultText is printed, the user edits it and presses enter, and the text as they've edited is assigned to editedText.

Is there a way to do this?
Thanks!

Nathan
  • 6,772
  • 11
  • 38
  • 55
  • 1
    Duplicate of this question: http://stackoverflow.com/questions/2533120/show-default-value-for-editing-on-python-input-possible – Mu Mind May 17 '11 at 16:25

1 Answers1

4

Yes, there is a way. Use readline

import readline

defaultText = 'I am the default value'
readline.set_startup_hook(lambda: readline.insert_text(defaultText))
res = raw_input('Edit this:')
print res

Note that this is not a terribly portable solution, and I've only tested it on Linux :)

x10
  • 3,820
  • 1
  • 24
  • 32
  • Looks great; I'll test it out as soon as I get home. I am curious, though, if there's a way to pull this off with the standard library (or at least with a more cross-platform package). Thanks! – Nathan May 17 '11 at 16:26
  • @Marco Really? The first line of the documentation linked: `Platforms: Unix`. – Nathan May 17 '11 at 16:29
  • @Luke Hey, that's true. I figured it wasn't because of the line I quoted above... So, is it compatible with just Unix (like that doc says) or with Win too? Note that it's in the [OS-dependent section](http://docs.python.org/library/someos.html). Thanks! – Nathan May 17 '11 at 16:34
  • 1
    There's a package `pyreadline` to provide readline-equivalent behaviour on Windows. It's installed along with IPython. AFAIK readline won't work on Windows without that. – Thomas K May 17 '11 at 17:01
  • @Marco @Luke Python 2.7 doesn't have the readline module in Windows here. What version are you using? Sure you haven't installed [readline.py](http://newcenturycomputers.net/projects/readline.html) or something like that? – Baffe Boyois May 17 '11 at 17:26
  • @x10 Not working OMM. I just get the 'edit this' part. Image of [IDLE](http://i.imgur.com/xAOps.png) (3.1.3) and [Terminal](http://i.imgur.com/vX1q0.png) (2.7.1). – Nathan May 18 '11 at 01:33
  • I don't know anything about macs, sorry :) Console input is a very platform-dependant topic, you could try adding a "mac" tag to the question and hope someone with Mac knowledge will come by :) – x10 May 18 '11 at 08:17