Integer File Descriptor “0” in open()

前端 未结 3 594
抹茶落季
抹茶落季 2020-12-03 14:52

In Python 3, it is possible to open a file object using an \"integer file descriptor\" with the format:

stdout = open(1, \"w\")
stdout.write(\"Hello World\")         


        
3条回答
  •  醉梦人生
    2020-12-03 15:52

    > syntax is handled by the shell before python is invoked. It connects stdout to the given file, as 2> does for stderr and < does for stdin.

    All that said, 0, 1, and 2 are file descriptors reserved for stdin, stdout, and stderr respectively (which is why 2> is the syntax to redirect stderr).

    So 0 is a valid file descriptor, but one that is your stdin, which you're opening again for writing. This ends up writing to the terminal it seems, since that's where stdin was going to write.

提交回复
热议问题