Strange behavior in Python 3 using the sys module

后端 未结 3 523
庸人自扰
庸人自扰 2020-12-11 20:30

While I was trying some stuffs in my Python 3 interpreter (Python 3.4.2, installed via brew), I encountered some weird outputs I didn\'t expected:

>>&g         


        
3条回答
  •  [愿得一人]
    2020-12-11 21:25

    This behaviour is normal. This happens because sys.stdout.write() returns the length of the text. Try this code again in a python file. you see, this doesn't happen anymore. This "weird stuff" happens because python automatically prints the return value unless you execute the code using a python file.

    >>>'text'
    'text'
    

    if you do this in a python file, there will be no result. you can prevent this by stopping the return such as this:

    >>>_=sys.stdout.write('text')
    

    or doing this:

    >>>def noreturn(value):
    ...    pass
    >>>noreturn(sys.stdout.write('text'))
    

提交回复
热议问题