使用stdout时的交互式用户输入

时间:2011-04-16 02:53:34

标签: python

在脚本中我使用sys.stdout.write()将处理后的数据输出到stdout,后来我在CLI上使用它将stdout重定向到文件:

python.exe script.py > file.out

我无法写入python脚本中的文件,因为无法知道重定向文件

我的问题是我也使用raw_input(),因为我需要用户在处理开始之前传递某些数字,但是当我重定向stdout时提示没有显示 - 即脚本等待用户输入但是没有显示任何内容

有人可以给我一个小费如何处理吗?

TIA

2 个答案:

答案 0 :(得分:2)

看看这是否适合你:

#!/usr/bin/python
import sys
import os
# Disable buffering for stdout
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
x = raw_input(">")
print x

将其运行为:

python ./test.py | tee ./file.out

现在,您将在控制台上看到您的输出,它也将被重定向到file.out。

答案 1 :(得分:0)

将文件名作为命令行参数,而不是重定向stdout。这样,您可以打印输出或正常使用raw_input()。例如:

import sys

outfile = open(sys.argv[1], 'w')
# write to the outfile
x = raw_input("What's your name?")
outfile.write(x)

用法:

python myscript.py file.out

这适用于任何平台。

相关问题