【发布时间】:2013-01-15 19:16:17
【问题描述】:
在 Java 中,我可以使用
将标准输出作为字符串读取ByteArrayOutputStream stdout = new ByteArrayOutputStream();
System.setOut(new PrintStream(stdout));
String toUse = stdout.toString();
/**
* do all my fancy stuff with string `toUse` here
*/
//Now that I am done, set it back to the console
System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
有人可以告诉我在 python 中执行此操作的等效方法吗?我知道这个问题的不同风格已经被问过很多次了,比如Python: Closing a for loop by reading stdout 和How to get stdout into a string (Python)。但是我有一种感觉,我不需要导入子流程来获得我需要的东西,因为我需要的比这更简单。我在eclipse上使用pydev,我的程序很简单。
我已经试过了
from sys import stdout
def findHello():
print "hello world"
myString = stdout
y = 9 if "ell" in myString else 13
但这似乎不起作用。我得到了一些关于打开文件的compaints。
【问题讨论】:
标签: java python string python-2.7 stdout