Python調用c++可執行程序

一、c++編譯程序python

#include <iostream>  
using namespace std; int test() { int a = 10, b = 5; return a+b; } int main() { cout<<"---begin---"<<endl; int num = test(); cout<<"num="<<num<<endl; cout<<"---end---"<<endl; }

g++ -o main_run main.cpp ios

 

二、python3調用c++可執行文件c++

# python3
import subprocess import os main = "./main_run"  
if os.path.exists(main): rc, out = subprocess.getstatusoutput(main) print('rc = %d, \nout = %s' % (rc, out) ) print( '*'*10 ) f = os.popen(main) data = f.readlines() f.close() print(data ) print( '*'*10 ) os.system(main)

命令結果:spa

c_py$ python3 -u py_call_c.py 
rc = 0, out = ---begin--- num=15
---end---
********** ['---begin---\n', 'num=15\n', '---end---\n'] **********
---begin--- num=15
---end---
相關文章
相關標籤/搜索