C、C++与Python的接口
我有一段C++代码,随着时间的推移变得越来越复杂。我有很多变量(主要是布尔类型),每次运行代码时都需要根据不同的运行条件来改变这些变量。之前我通过命令行输入参数来实现这一点,使用的是main( int argc, char* argv[])
这个函数。
不过这种方法现在变得有些麻烦了,因为我有18种不同的运行条件,所以需要18个不同的参数 :-( 。我想换个方式,考虑用Python来处理(如果需要的话,也可以用Bash)。理想情况下,我希望能写一个Python脚本,在里面设置数据成员的值,然后再运行我的C++代码。
有没有人能给我一些建议或者信息来帮助我?如果能提供一个简单的代码示例或者相关的网址就更好了。
对原问题的补充:
抱歉,我觉得我之前的问题不够清楚。我不想在C++中使用main( int argc, char* argv[])
这个功能。也就是说,我不想在命令行上设置变量。请问我能否用Python来声明和初始化我C++代码中的数据成员?
再次感谢,Mike
6 个回答
3
你可以使用subprocess模块来启动一个可执行文件,并且可以定义一些命令行参数:
import subprocess
option1 = True
option2 = Frue
# ...
optionN = True
lstopt = ['path_to_cpp_executable',
option1,
option2,
...
optionN
]
lstopt = [str(item) for item in lstopt] # because we need to pass strings
proc = subprocess.Popen(lstrun, close_fds = True)
stdoutdata, stderrdata = proc.communicate()
如果你使用的是Python 2.7或者Python 3.2版本,那么使用OrderedDict会让代码更容易阅读:
from collections import OrderedDict
opts = OrderedDict([('option1', True),
('option2', False),
]
lstopt = (['path_to_cpp_executable'] +
list(str(item) for item in opts.values())
)
proc = subprocess.Popen(lstrun, close_fds = True)
stdoutdata, stderrdata = proc.communicate()
8
用subprocess模块在Python中执行你的程序。
import subprocess as sp
import shlex
def run(cmdline):
process = sp.Popen(shlex.split(cmdline), stdout=sp.PIPE, stderr=sp.PIPE)
output, err = process.communicate()
retcode = process.poll()
return retcode, output, err
run('./a.out '+arg1+' '+arg2+' '+...)
6
在C/C++和Python之间的连接有很多文档说明,方法也不少。不过,如果你只是想设置一些值,使用Python可能有点过于复杂,因为Python更适合处理一些大规模的操作,通常是把这些操作交给解释器来完成。
我个人建议你可以研究一下“ini”文件的方法,这种方法可以是传统的ini文件格式,也可以使用XML,甚至可以考虑用一种更轻量的脚本语言,比如Lua。