Backwards-compatible input calls in Python

后端 未结 4 1740
囚心锁ツ
囚心锁ツ 2020-12-01 18:12

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 l

4条回答
  •  离开以前
    2020-12-01 18:34

    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.

提交回复
热议问题