consistent input() for Python 2 and 3

Jason Swails jason.swails at gmail.com
Thu Aug 2 14:34:11 CEST 2012


On Thu, Aug 2, 2012 at 5:49 AM, Ulrich Eckhardt <
ulrich.eckhardt at dominolaser.com> wrote:

> Hi!
>
> I'm trying to write some code that should work with both Python 2 and 3.
> One of the problems there is that the input() function has different
> meanings, I just need the raw_input() behaviour of Python 2.
>
>
> My approach is to simply do this:
>
>   try:
>       # redirect input() to raw_input() like Python 3
>       input = raw_input
>   except NameError:
>       # no raw input, probably running Python 3 already
>       pass
>
>
> What do you think? Any better alternatives?
>

Depending on how much user input is needed in your application, you can
always use the 'cmd' module: http://docs.python.org/library/cmd.html

It is present in both Python 2 and Python 3 and should just 'do the right
thing'.  It also seamlessly integrates readline (if present),
command-completion, and provides a built-in help menu for defined commands.

It's written in pure Python, and in my opinion, the best form of
documentation for that module is the source code itself.

I haven't used it in Python 3, but I imagine it can be used in a way that
easily supports Python 2 and 3.  If you have only one or two places where
you need user-input, this is probably overkill.

HTH,
Jason
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120802/8bf175e7/attachment.html>


More information about the Python-list mailing list