我遇到了一些问题。这里是我的代码:python:在exec语句中获取打印输出
code = """
i = [0,1,2]
for j in i :
print j
"""
result = exec(code)
我怎么能得到打印输出的东西? 我怎样才能得到这样的:
0
1
2
的问候和感谢,
我遇到了一些问题。这里是我的代码:python:在exec语句中获取打印输出
code = """
i = [0,1,2]
for j in i :
print j
"""
result = exec(code)
我怎么能得到打印输出的东西? 我怎样才能得到这样的:
0
1
2
的问候和感谢,
我有同样的想法弗雷德里克,但我写了一个上下文管理器来处理代替标准输出:
import sys
import StringIO
import contextlib
@contextlib.contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = StringIO.StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
code = """
i = [0,1,2]
for j in i :
print j
"""
with stdoutIO() as s:
exec code
print "out:", s.getvalue()
喜欢的东西:
codeproc = subprocess.Popen(code, stdout=subprocess.PIPE)
print(codeproc.stdout.read())
应该在不同的工艺和管执行代码的输出回你的主程序通过codeproc.stdout
。但我没有亲自使用过它,所以如果有什么东西我做错随时指出来:P
我必须这样做在python只:/谢谢你的答案 – user462794 2010-10-11 12:48:08
这是唯一的蟒蛇:P – Blam 2010-10-11 12:52:56
我有一个: codeproc = subprocess.Popen(命令,stdout = subprocess.PIPE) 文件“C:\ DEV \ Python27 \ lib \ subprocess.py”,行672,在__init__中 errread,errwrite) 文件“C:\ DEV \ Python27 \ lib \ subprocess.py ”行882,在_execute_child STARTUPINFO) WindowsError:[错误2]乐fichierspécifiéEST introuvable(文件法文未找到) – user462794 2010-10-11 13:32:36
您可以将标准输出重定向到的exec调用的持续时间的字符串:
code = """
i = [0,1,2]
for j in i :
print j
"""
from cStringIO import StringIO
old_stdout = sys.stdout
redirected_output = sys.stdout = StringIO()
exec(code)
sys.stdout = old_stdout
print redirected_output.getvalue()
只是想补充说明的是,使这条巨蟒3的朋友你必须从'io' =>'从io import StringIO'中导入'StringIO'。 – idjaw 2016-09-13 01:53:09
这里是PY3友好的@乔臣的回答版本。我还添加了try-except
子句以在code
中发生错误时进行恢复。
import sys
from io import StringIO
import contextlib
@contextlib.contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
code = """
i = [0,1,2]
for j in i :
print(j)
"""
with stdoutIO() as s:
try:
exec(code)
except:
print("Something wrong with the code")
print "out:", s.getvalue()
这是Frédéric的回答的一个小小的更正。我们需要在exec()
中处理可能的异常,以恢复正常stdout
。否则,我们无法看得更远print
输出:
code = """
i = [0,1,2]
for j in i :
print j
"""
from cStringIO import StringIO
old_stdout = sys.stdout
redirected_output = sys.stdout = StringIO()
try:
exec(code)
except:
raise
finally: # !
sys.stdout = old_stdout # !
print redirected_output.getvalue()
...
print 'Hello, World!' # now we see it in case of the exception above
非常感谢很多 – user462794 2010-10-11 13:08:25
我有一个:文件“D:\ Documents \ perso \ dev \ meta \ Server.py”,第77行,在decompress_html 与self.stdoutIO()作为s: AttributeError:__exit__ – user462794 2010-10-11 13:26:21
@ user462794:你似乎忽略了@ @ contextlib.contextmanager行 – 2010-10-11 16:19:46