How can I tell new Python to use the old print - python

The print function's syntax has been changed in newer versions of python. The problem is that at home, I have the newer version of python while at office the old one. How can I have the same program run on both the newer and old python versions?

If you're using iPython/ Jupyter, run
%autocall 1
After that, you can use
print "yo"
like in Python 2.

Many 2 vs 3 porting issues are covered well here.
In general, I think it's more hassle than it's worth to try to keep a single .py file that runs under both versions. But if you want to try, that link shows usable workarounds.
While it's true that Python 2 supports, for example,
print("abc", 3)
the results aren't the same: in Python 2 that prints the tuple ('abc', 3). And Python 2's print doesn't support Python 3's optional keyword arguments at all (like file=).

You can use new print syntax on older version of python.

You can use the new print function in old scripts like this:
# This line goes at the top of the file ...
from __future__ import print_function
# And then you can use the new-style print function anywhere
print("hello")

Related

Getting input from user without using "input" function [duplicate]

I was wondering if anyone has suggestions for writing a backwards-compatible input() call for retrieving a filepath?
In Python 2.x, raw_input worked fine for input like /path/to/file. Using input works fine in this case for 3.x, but complains in 2.x because of the eval behavior.
One solution is to check the version of Python and, based on the version, map either input or raw_input to a new function:
if sys.version_info[0] >= 3:
get_input = input
else:
get_input = raw_input
I'm sure there is a better way to do this though. Anyone have any suggestions?
Since the Python 2.x version of input() is essentially useless, you can simply overwrite it by raw_input:
try:
input = raw_input
except NameError:
pass
In general, I would not try to aim at code that works with both, Python 2.x and 3.x, but rather write your code in a way that it works on 2.x and you get a working 3.x version by using the 2to3 script.
This code is taught in many Python education and training programs now.
Usually taught together:
from __future__ import print_function
if hasattr(__builtins__, 'raw_input'):
input = raw_input
First line: imports the Python 3.x print() function into Python 2.7 so print() behaves the same under both versions of Python. If this breaks your code due to older print "some content" calls, you can leave this line off.
Second and third lines: sets Python 2.7 raw_input() to input() so input() can be used under both versions of Python without problems. This can be used all by itself if this is the only compatibility fix you wish to include in your code.
There are more from __future__ imports available on the Python.org site for other language compatibility issues. There is also a library called "six" that can be looked up for compatibility solutions when dealing with other issues.
The way you are handling it is just fine. There are probably more similar ways using the sys module, but just in keep in mind that if you are program is doing something more than trivial with strings and files, it is better to have two versions of your program instead of having a backwards compatible python3 program.
You could import the function:
from builtins import input
Unfortunately though this method requires an external dependency via pip install future

Syntax error, print with sep= statement

First and foremost i am very new into Python. I am using a notebook version of Ipython called jupyter and its provided by my University, so I don't know whether this is a standard version or not.
I was busy in a slide course about Python and encountered this exercice:
This is the code I used and the syntax error I get
in the Ipython environment
I don't get why it is not working.
Thank you in advance
Olivier
print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout]) is a function in Python 3.x, which has a sep keyword argument (among others).
If you are using Python 2.7 (try print "Hello!" - if it runs, you have Python 2.x), print is a statement there, which means that if you want to get the behaviour as in your slide (make print a function), you need to import print_function from __future__ module.
That way you can use print("Hi!", "Hello!", sep='\t') as in your slide.
As mentioned by #Kevin in his comment below this post, if your course uses Python 3.x, you would be better off to upgrade to this version since things like async, yield from or lzma are not available in Python 2.x.

Forward-compatible print statement in python 2.5

OK, maybe I'm just having an off day. This seems like something a lot of people must be asking, but Google is failing me horribly. The closest thing I found was this which doesn't exactly address this issue.
At work I run Arch on my desktop (which is python 3 by default), and Debian Lenny on my company's servers (which is python 2.5). I want to write a single python script that will work in both python 2 and 3. It's a very simple script, not much to it (mostly it just calls off to git using subprocess). Everything already works in both versions of python EXCEPT for the damned print statements.
Everyone out there seems to suggest the from __future__ import print_function trick. However this was introduced in python 2.6, and I'm stuck with 2.5.
So what are my options? How can I call print in both 2.5 and 3 using the same script? I was thinking maybe some kind of wrapper function, but this might not be the most "pythonic" way of doing things. Your thoughts? And no, upgrading the server to 2.6 isn't an option.
Thanks!
print("hi") works on both py 2 and 3 without from __future__ in py 2.5
alternatively, although not recommended:
import sys
sys.stdout.write("hi")
Why don't you just use the logging framework? It mitigates your issue, and is much better than print statements littered throughout the code.
This works for me:
import sys
if sys.version_info[0] == 2:
def print_(*args):
w = sys.stdout.write
w( ', '.join(str(a) for a in args) )
w( '\n' )
else:
print_ = getattr(__builtins__, 'print')
If you need the full featured print functionality, you're better off using the print_ from six. In this case,
from six import print_
// replace all "print ..." by "print_(...)"

Backwards-compatible input calls in Python

I was wondering if anyone has suggestions for writing a backwards-compatible input() call for retrieving a filepath?
In Python 2.x, raw_input worked fine for input like /path/to/file. Using input works fine in this case for 3.x, but complains in 2.x because of the eval behavior.
One solution is to check the version of Python and, based on the version, map either input or raw_input to a new function:
if sys.version_info[0] >= 3:
get_input = input
else:
get_input = raw_input
I'm sure there is a better way to do this though. Anyone have any suggestions?
Since the Python 2.x version of input() is essentially useless, you can simply overwrite it by raw_input:
try:
input = raw_input
except NameError:
pass
In general, I would not try to aim at code that works with both, Python 2.x and 3.x, but rather write your code in a way that it works on 2.x and you get a working 3.x version by using the 2to3 script.
This code is taught in many Python education and training programs now.
Usually taught together:
from __future__ import print_function
if hasattr(__builtins__, 'raw_input'):
input = raw_input
First line: imports the Python 3.x print() function into Python 2.7 so print() behaves the same under both versions of Python. If this breaks your code due to older print "some content" calls, you can leave this line off.
Second and third lines: sets Python 2.7 raw_input() to input() so input() can be used under both versions of Python without problems. This can be used all by itself if this is the only compatibility fix you wish to include in your code.
There are more from __future__ imports available on the Python.org site for other language compatibility issues. There is also a library called "six" that can be looked up for compatibility solutions when dealing with other issues.
The way you are handling it is just fine. There are probably more similar ways using the sys module, but just in keep in mind that if you are program is doing something more than trivial with strings and files, it is better to have two versions of your program instead of having a backwards compatible python3 program.
You could import the function:
from builtins import input
Unfortunately though this method requires an external dependency via pip install future

How to write a Python 2.6+ script that gracefully fails with older Python?

I'm using the new print from Python 3.x and I observed that the following code does not compile due to the end=' '.
from __future__ import print_function
import sys
if sys.hexversion < 0x02060000:
raise Exception("py too old")
...
print("x",end=" ") # fails to compile with py24
How can I continue using the new syntax but make the script fails nicely? Is it mandatory to call another script and use only safe syntax in this one?
The easy method for Python 2.6 is just to add a line like:
b'You need Python 2.6 or later.'
at the start of the file. This exploits the fact that byte literals were introduced in 2.6 and so any earlier versions will raise a SyntaxError with whatever message you write given as the stack trace.
There are some suggestions in this question here, but it looks like it is not easily possible. You'll have to create a wrapper script.
One way is to write your module using python 2.x print statement, then when you want to port it into python 3, you use 2to3 script. I think there are scripts for 3to2 conversion as well, although they seems to be less mature than 2to3.
Either way, in biggers scripts, you should always separate domain logic and input/output; that way, all the print statements/functions are bunched up together in a single file. For logging, you should use the logging module.

Categories