python - 运行带有参数的 python 脚本

标签 python c eclipse

我想从 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/

相关文章:

python - 无法使用 kubernetes python 客户端创建 CRD

python - 如何在 Azure 应用服务中将 OpenCV 与 Python 结合使用?

java - 如何在处置时删除 Eclipse Widget 中的监听器?

Android list 文件不同步

java - 在 Eclipse 中查找导致 NPE 的方法

python - 计算检测到的物体像素数占图片总像素数的百分比

python - np.where 中的 Pandas GROUPBY

c - 立即创建结构体变量和稍后创建变量有什么区别?

c - 寻找奇数的中间数

c - 为什么第一个 sbrk 的返回值与后续调用不同?