2010-10-11 47 views
20

我遇到了一些問題。這裏是我的代碼:python:在exec語句中獲取打印輸出

code = """ 
i = [0,1,2] 
for j in i : 
    print j 
""" 
result = exec(code) 

我怎麼能得到打印輸出的東西? 我怎樣才能得到這樣的:

0 
1 
2 

的問候和感謝,

回答

31

我有同樣的想法弗雷德裏克,但我寫了一個上下文管理器來處理代替標準輸出:

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() 
+0

非常感謝很多 – user462794 2010-10-11 13:08:25

+0

我有一個:文件「D:\ Documents \ perso \ dev \ meta \ Server.py」,第77行,在decompress_html 與self.stdoutIO()作爲s: AttributeError:__exit__ – user462794 2010-10-11 13:26:21

+0

@ user462794:你似乎忽略了@ @ contextlib.contextmanager行 – 2010-10-11 16:19:46

1

喜歡的東西:

codeproc = subprocess.Popen(code, stdout=subprocess.PIPE) 
print(codeproc.stdout.read()) 

應該在不同的工藝和管執行代碼的輸出回你的主程序通過codeproc.stdout。但我沒有親自使用過它,所以如果有什麼東西我做錯隨時指出來:P

+0

我必須這樣做在python只:/謝謝你的答案 – user462794 2010-10-11 12:48:08

+0

這是唯一的蟒蛇:P – Blam 2010-10-11 12:52:56

+0

我有一個: 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

7

您可以將標準輸出重定向到的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() 
+2

只是想補充說明的是,使這條巨蟒3的朋友你必須從'io' =>'從io import StringIO'中導入'StringIO'。 – idjaw 2016-09-13 01:53:09

2

這裏是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() 
1

這是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