consistent input() for Python 2 and 3

  • Thread starter Ulrich Eckhardt
  • Start date
U

Ulrich Eckhardt

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?

Uli
 
P

Philipp Hagemeister

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?

That's the generic solution, see
http://python3porting.com/differences.html#input-and-raw-input .

In my experience, it seems that input's main function is to allow
beginners to learn the language, or to be used in short scripts. For a
serious application, either curses or moving the input to the invocation
arguments is often a better choice.

- Philipp


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.12 (GNU/Linux)

iEYEAREKAAYFAlAaX5EACgkQ9eq1gvr7CFzWGQCcCq0Fki1F1dSlWAgMOqgW/fU+
Z5gAn0twjLG6nElB0XDvDcVqe79Fswzu
=q1wr
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top