Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 重定向标准输出时打印到终端_Python_Unix - Fatal编程技术网

Python 重定向标准输出时打印到终端

Python 重定向标准输出时打印到终端,python,unix,Python,Unix,我有一个小的命令行脚本,它将结果打印到stdout,然后我通常将其重定向到一个文件。脚本的一部分是需要通过终端向用户请求一些输入,但输入提示当然也会重定向到文件,因此用户不知道该做什么: 鸡蛋 如何使输入promt指向终端,而不管stdout指向何处,以便: python eggs.py > test.txt > Eggs and Spam? 和test.txt: 它可能并不完全用于向终端显示内容,但使用stderr可以实现您想要的功能: import sys if __name

我有一个小的命令行脚本,它将结果打印到stdout,然后我通常将其重定向到一个文件。脚本的一部分是需要通过终端向用户请求一些输入,但输入提示当然也会重定向到文件,因此用户不知道该做什么:

鸡蛋

如何使输入promt指向终端,而不管stdout指向何处,以便:

python eggs.py > test.txt
> Eggs and Spam?
和test.txt:


它可能并不完全用于向终端显示内容,但使用stderr可以实现您想要的功能:

import sys

if __name__ == "__main__":
    print("foo")
    print("Eggs and spam?", file=sys.stderr)
    choice = input()
    print("bar")

更好的设计是摆脱交互式I/O,让用户将任何参数或输入指定为命令行参数或输入文件。在这种情况下,我需要用户决定一个数据点应该留在数据集中还是应该忽略它。这不能预先决定。这也是我的第一个想法,但是一旦stderr也被重定向到日志文件,这就又成问题了。如果您可以与调用者合作,他们可以在运行脚本之前打开其他文件描述符。或者,您可以任意地编写到
/dev/tty
,并希望它被定义。(有很多方法可以检查,但当它不是终端时,没有好的方法可以后退。)
foo
bar
import sys

if __name__ == "__main__":
    print("foo")
    print("Eggs and spam?", file=sys.stderr)
    choice = input()
    print("bar")