我想知道这是否可能在python中.
# module1
def test():
print('hey')
# module2
import module1
module1.test() # prints to stdout
Run Code Online (Sandbox Code Playgroud)
谢谢!
Ala*_*nSE 22
我不想负责修改sys.stdout然后将其恢复到以前的值。上面的答案没有任何finally:条款,将其集成到其他重要代码中可能会很危险。
https://docs.python.org/3/library/contextlib.html
import contextlib, io
f = io.StringIO()
with contextlib.redirect_stdout(f):
module1.test()
output = f.getvalue()
Run Code Online (Sandbox Code Playgroud)
你可能希望变量output是<class 'str'>与重定向标准输出。
注意:此代码是从官方文档中提取的,做了一些简单的修改(但经过测试)。这个答案的另一个版本已经给出了一个大部分重复的问题:https : //stackoverflow.com/a/22434594/1092940
我将答案留在这里,因为它比 IMO 的其他解决方案要好得多。
dro*_*dri 19
是的,您只需要将stdout重定向到符合stdout接口的内存缓冲区,您可以使用StringIO执行此操作.这适用于2.7:
import sys
import cStringIO
stdout_ = sys.stdout #Keep track of the previous value.
stream = cStringIO.StringIO()
sys.stdout = stream
print "hello" # Here you can do whatever you want, import module1, call test
sys.stdout = stdout_ # restore the previous stdout.
variable = stream.getvalue() # This will get the "hello" string inside the variable
Run Code Online (Sandbox Code Playgroud)
g.d*_*d.c 13
是的你可以.你需要掌控sys.stdout.像这样的东西:
import sys
stdout_ = sys.stdout #Keep track of the previous value.
sys.stdout = open('myoutputfile.txt', 'w') # Something here that provides a write method.
# calls to print, ie import module1
sys.stdout = stdout_ # restore the previous stdout.
Run Code Online (Sandbox Code Playgroud)
对于Python 3:
# redirect sys.stdout to a buffer
import sys, io
stdout = sys.stdout
sys.stdout = io.StringIO()
# call module that calls print()
import module1
module1.test()
# get output and restore sys.stdout
output = sys.stdout.getvalue()
sys.stdout = stdout
print(output)
Run Code Online (Sandbox Code Playgroud)
小智 5
不需要使用另一个模块,只需使用具有 write 属性的类对象,一个输入,您可以将其保存在另一个变量中。为营地
班级:
class ExClass:
def __init__(self):
self.st = ''
def write(self, o): #here o is the output that goes to stdout
self.st += str(o)
Run Code Online (Sandbox Code Playgroud)
主要程序:
import sys
stdout_ = sys.stdout
var = ExClass()
sys.stdout = var
print("Hello") # these will not be pronted
print("Hello2") # instead will be written in var.st
sys.stdout = stdout_
print(var.st)
Run Code Online (Sandbox Code Playgroud)
输出将是
Hello
Hello2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14839 次 |
| 最近记录: |