from __future__ import

from __future__ import

  I saw it in the process of reading the code, and I searched it out of curiosity. In fact, when we debug other people's Python code, we often encounter some problems, such as different versions, and the code will also change. For example, the Python 2.7 version of the print function is print " " , Python 3.0 and above is print (" "). Is there any solution?

Python 3.x introduced some keywords and features that were incompatible with Python 2. In Python 2, these new things can be imported through the built-in __future__ module. If you want code written in Python 2 to run in Python 3.x, it is recommended to use the __future__ module. For example, if you want to have the integer division behavior of Python 3.x in Python 2 , you can import the corresponding module with the following statement.

Take from __future__ import print_function as an example:

  • This is the concept of python 2, obviously python 3 is a future for python2
  • This sentence must be placed at the head of the file

Specify the file keyword parameter, and print to the file stream, of course, it can also be the standard input and output stream

from __future__ import print_function
import sys
print('error happens!', file=sys.stderr)

这样通过form_future_import模块就可以使在Python2.7环境下的代码也可以在Python3.0以上版本中运行了!