我想从C调用Python脚本,传递脚本中需要的一些参数
我要使用的脚本是mrsync,或multicast remote sync。我在命令行中通过调用:
python mrsync.py -m /tmp/targets.list -s /tmp/sourcedata -t /tmp/targetdata
-m is the list containing the target ip-addresses. -s is the directory that contains the files to be synced. -t is the directory on the target machines where the files will be put.
到目前为止,我通过使用以下C程序,成功地运行了一个没有参数的Python脚本:
Py_Initialize();
FILE* file = fopen("/tmp/myfile.py", "r");
PyRun_SimpleFile(file, "/tmp/myfile.py");
Py_Finalize();
这个很好用。但是,我找不到如何将这些参数传递给PyRun_SimpleFile(..)
方法
你有两个选择
召唤
在你的C代码中
实际使用
mrsync
(希望如此)定义的API。这更灵活,但要复杂得多。第一步是确定如何以Python函数调用的形式执行上述操作。如果mrsync
写得很好,那么将有一个函数mrsync.sync
(比如)作为一旦您了解了如何做到这一点,就可以使用Python API直接从C代码调用该函数
看起来您正在使用python.h中的python开发API寻找答案。下面是一个应该有效的示例:
然后是传递这些参数的C代码:
如果可以将参数传递到C函数中,则此任务将变得更加简单:
你可以直接穿过去。现在,为了节省时间,我的解决方案只使用了2个命令行参数,但是您可以对所有需要通过的6个命令行参数使用相同的概念。。。当然,在python端也有更干净的方法来捕获参数,但这只是基本的想法
希望有帮助
相关问题 更多 >
编程相关推荐