2016-08-05 54 views
0

我有一個R函數,我使用rpy2從我的Python腳本調用。 R函數打印到stdout; rpy2中有一個參數,它在R腳本被調用時使stdout靜音?如何將輸出沉默到rpy2的stdout?

+0

您可以使用'StringIO'來停止'stdout'寫入。在「StringIo」模塊中的Python 2中,以及在「io」模塊中的Python 3中。 – cdarke

+0

在R方面,您可以使用'不可見(表達式)'來隱藏打印方法 – Shape

回答

0

rpy2讓你重新定義R作爲python函數與終端自己的交互。

從文檔以下示例顯示瞭如何將輸出附加 到stdout到Python列表(在事物的宏偉計劃用途有限,但它使所述特徵的簡單的例子):

buf = [] 
def f(x): 
    # function that append its argument to the list 'buf' 
    buf.append(x) 

# output from the R console will now be appended to the list 'buf' 
rinterface.set_writeconsole(f) 

date = rinterface.baseenv['date'] 
rprint = rinterface.baseenv['print'] 
rprint(date()) 

# the output is in our list (as defined in the function f above) 
print(buf) 


# restore default function 
rinterface.set_writeconsole(rinterface.consolePrint) 

文檔位於:http://rpy2.readthedocs.io/en/version_2.8.x/callbacks.html#console-i-o