使用C API将命令行参数传递给python 2.7.6软件包应用程序 [英] Pass command line arguments to python 2.7.6 package application using C API

查看:74
本文介绍了使用C API将命令行参数传递给python 2.7.6软件包应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,现在我需要使用其C API调用python 2.7.6程序.

I'm new to python and now I need to call a python 2.7.6 program using its C API.

python程序采用 python包的形式,并且需要几个命令行选项.您可以这样运行它:

The python program is in the form of a python package and takes several command line options. You can run it like this:

python my_py_app input.txt --option1="value1" --option2="value2"

这就是我一直在做的事情:

Here's what I've been doing:

1,使用Py_Initialize()设置python API;

1, Setup python API using Py_Initialize();

2,使用PyImport_ImportModule("my_py_app")加载该程序包,并返回有效的PyObject

2, Load that package using PyImport_ImportModule("my_py_app") and it returns a valid PyObject

3,我不知道该如何进行...

3, I don't know how to proceed ...

python C API文档包含许多功能,例如PyEval_CallXXX.我需要调用哪一个,如何将选项/值对传递给程序?

The python C API document contains lots of functions like PyEval_CallXXX. Which one do I need to call and how do I pass the option/value pairs to the program?

推荐答案

您正在寻找 PySys_SetArgv 函数.

以下问题提供了更多信息和示例:

The following question has some more information and an example:

运行带有参数的python脚本

$ find
.
./py.c
./mymod
./mymod/__init__.py
./mymod/__main__.py
$ cat ./mymod/__init__.py
$ cat ./mymod/__main__.py
import sys

print 'hello', ' '.join(sys.argv[1:])
$ python mymod world
hello world
$ cat ./py.c
#include <stdio.h>
#include <python2.7/Python.h>

int main(void)
{
    int argc;
    char * argv[2];

    argc = 2;
    argv[0] = "mymod";
    argv[1] = "world";

    Py_SetProgramName(argv[0]);
    Py_Initialize();
    PySys_SetArgv(argc, argv);
    PyImport_ImportModule("mymod.__main__");
    Py_Finalize();

    return 0;
}
$ gcc `python2.7-config --cflags --ldflags` py.c
$ ./a.out
hello world
$

这篇关于使用C API将命令行参数传递给python 2.7.6软件包应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆