Python 3 operator >> to print to file

后端 未结 3 1072
遇见更好的自我
遇见更好的自我 2020-12-29 20:38

I have the following Python code to write dependency files of a project. It works fine with Python 2.x, but while testing it with Python 3 it reports an error.



        
相关标签:
3条回答
  • 2020-12-29 20:58

    Note that starting in Python 3.6.3 (September 2017), the error message for this case will be changing to recommend the Python 3 spelling:

    >>> print >> sys.stderr
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unsupported operand type(s) for >>:
        'builtin_function_or_method' and '_io.TextIOWrapper'.
        Did you mean "print(<message>, file=<output_stream>)"?
    

    (Explicit line breaks added to avoid side-scrolling - the actual error message just wraps at the width of your terminal window)

    0 讨论(0)
  • 2020-12-29 21:01

    In Python 3 the print statement has become a function. The new syntax looks like this:

    print(s, end="", file=depend)
    

    This breaking change in Python 3 means that it is not possible to use the same code in Python 2 and 3 when writing to a file using the print statement/function. One possible option would be to use depend.write(s) instead of print.

    Update: J.F. Sebastian correctly points out that you can use from __future__ import print_function in your Python 2 code to enable the Python 3 syntax. That would be an excellent way to use the same code across different Python versions.

    0 讨论(0)
  • 2020-12-29 21:13

    print() is a function in Python 3.

    Change your code to print(s, end="", file=depend), or let the 2to3 tool do it for you.

    0 讨论(0)
提交回复
热议问题