我想从 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(..)
方法。
最佳答案
您似乎正在使用 Python.h 中的 Python 开发 API 寻找答案。这是一个应该可以工作的示例:
#My python script called mypy.py
import sys
if len(sys.argv) != 2:
sys.exit("Not enough args")
ca_one = str(sys.argv[1])
ca_two = str(sys.argv[2])
print "My command line args are " + ca_one + " and " + ca_two
然后是传递这些参数的 C 代码:
//My code file
#include <stdio.h>
#include <python2.7/Python.h>
void main()
{
FILE* file;
int argc;
char * argv[3];
argc = 3;
argv[0] = "mypy.py";
argv[1] = "-m";
argv[2] = "/tmp/targets.list";
Py_SetProgramName(argv[0]);
Py_Initialize();
PySys_SetArgv(argc, argv);
file = fopen("mypy.py","r");
PyRun_SimpleFile(file, "mypy.py");
Py_Finalize();
return;
}
如果您可以将参数传递到您的 C 函数中,这项任务将变得更加容易:
void main(int argc, char *argv[])
{
FILE* file;
Py_SetProgramName(argv[0]);
Py_Initialize();
PySys_SetArgv(argc, argv);
file = fopen("mypy.py","r");
PyRun_SimpleFile(file, "mypy.py");
Py_Finalize();
return;
}
你可以直接通过。现在我的解决方案出于时间原因只使用了 2 个命令行参数,但是您可以对需要传递的所有 6 个参数使用相同的概念......当然还有更简洁的方法可以在 python 端捕获参数,但是这只是基本的想法。
希望对你有帮助!
关于python - 运行带有参数的 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12142174/