运行带参数的python脚本

2024-10-05 14:30:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从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(..)方法。


Tags: thepy脚本target参数isfilesbe
2条回答

你有两个选择。

  1. 呼叫

    system("python mrsync.py -m /tmp/targets.list -s /tmp/sourcedata -t /tmp/targetdata")
    

    在你的C代码里。

  2. 实际使用mrsync(希望)定义的API。这更灵活,但复杂得多。第一步是确定如何作为Python函数调用执行上述操作。如果mrsync写得很好,就会有一个函数mrsync.sync(比方说)被称为

    mrsync.sync("/tmp/targets.list", "/tmp/sourcedata", "/tmp/targetdata")
    

    一旦您了解了如何做到这一点,就可以使用Python API从C代码直接调用该函数。

似乎您正在使用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端也有更干净的方法来捕获args,但这只是基本的想法。

希望有帮助!

相关问题 更多 >