相关疑难解决方法(0)

open()中的整数文件描述符"0" - Python 3

在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 …

python bash stdout python-3.x python-internals

8
推荐指数
1
解决办法
1162
查看次数

标签 统计

bash ×1

python ×1

python-3.x ×1

python-internals ×1

stdout ×1