我想从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端也有更干净的方法来捕获args,但这只是基本的想法。
希望有帮助!
相关问题 更多 >
编程相关推荐