在Java中,我可以使用以下方式将stdout读取为字符串:
请问有没有人可以展示一下在Python中实现同样功能的等效方法呢?我知道这种问题已经被问了很多次,比如Python: Closing a for loop by reading stdout和How to get stdout into a string (Python)。但是我感觉我不需要导入subprocess来得到我想要的结果,因为我的需求比那更简单。我正在使用eclipse上的pydev,并且我的程序非常简单。
我已经尝试过
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)。但是我感觉我不需要导入subprocess来得到我想要的结果,因为我的需求比那更简单。我正在使用eclipse上的pydev,并且我的程序非常简单。
我已经尝试过
from sys import stdout
def findHello():
print "hello world"
myString = stdout
y = 9 if "ell" in myString else 13
但是似乎这并没有起作用。我收到了一些关于打开文件的投诉。