我已经在C++中使用Boosi.Python脚本中有工作函数。p>
此函数正在向我打印一些数据(字符串) 要调用此函数,我使用以下代码:
import cpp as cpp_fun #importing from c++ already compiled with boost (no exe)
file = path_to_file #doesn't matter which file
cpp_fun.strings(file)#gives me output
output:
"this is test string, one line of many.."
我甚至不需要使用print(cpp_fun.strings())
来打印输出,所以问题是,
我不能将它添加到变量中,然后打印这个变量,因为当我运行python时,这个函数一直在打印输出
我想将输出从cpp_fun.strings()
保存到变量
但是当我做的时候:
strings = cpp_fun.strings()
它再次给我输出
我试图创建方法(def()
)并将此函数放入其中,但结果还是一样的,
我还尝试捕捉输出:
old_stdout = sys.stdout
new_stdout = StringIO()
sys.stdout = new_stdout
print(cp_fun.strings())
output = new_stdout.getvalue()
sys.stdout = old_stdout
但是,如果没有成功,上面的这个捕获对普通打印有效,但对这一个无效。
我还尝试添加了var=subprocess.check_output([cpp_fun])
-不起作用
也许你有办法把它保存到变量中
将cpp扩展模块替换为一个普通的Python扩展模块,它只打印作为参数接收的文件的每一行
下面是捕获其输出的示例
cpp.py:
code00.py:
输出:
更新#0
将代码更改为同时捕获函数的stderr
更新#1
添加基于[Python 3.Docs]: subprocess - Subprocess management的变量(这在我这边也适用)。这需要一个额外的脚本(cpp\u wrapper.py,它依赖于上面的cpp.py)
cpp_wrapper.py:
code01.py:
输出:
相关问题 更多 >
编程相关推荐