在Python 3中,可以使用"整数文件描述符"打开文件对象,格式为:
stdout = open(1, "w")
stdout.write("Hello World") # Prints Hello World
stdout.close()
Run Code Online (Sandbox Code Playgroud)
虽然,有趣的是,我发现这0也是一个有效的流.
如果我把它放在文件中testio.py:
stdout = open(0, "w")
stdout.write("Foo Bar\n")
stdout.close()
Run Code Online (Sandbox Code Playgroud)
然后运行该代码输出是:
bash-3.2$ python3 testio.py
Foo Bar
Run Code Online (Sandbox Code Playgroud)
这似乎就像stdout.然而...
bash-3.2$ python3 testio.py > testio.txt
Foo Bar
bash-3.2$ cat testio.txt
Run Code Online (Sandbox Code Playgroud)
所以看起来这实际上不是stdout,而是其他东西.它似乎也不stderr是:
bash-3.2$ python3 testio.py 2> testio.txt
Foo Bar
bash-3.2$ cat testio.txt
Run Code Online (Sandbox Code Playgroud)
但是,我确实发现输出可以使用0>以下方式重定向:
bash-3.2$ python3 testio.py 0> testio.txt
bash-3.2$ cat testio.txt
Foo Bar
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,究竟到底open(0, "w")应有的是什么?什么是重定向的"0>"流?
Python …