【问题标题】:Excluding non-relevant parameters when using PyArg_ParseTupleAndKeywords使用 PyArg_ParseTupleAndKeywords 时排除不相关的参数
【发布时间】:2011-11-02 13:28:40
【问题描述】:

在嵌入式 Python 场景中,我们使用 PyArg_ParseTupleAndKeywords 从 Python(版本 >=3 .x)接收数据并将其用于 C++ 应用程序。

目前我们有类似的设置:

PyObject* whatever(PyObject *self, PyObject *args, PyObject *keywds) {
    ....
    static char* kwlist[] = { "foo", "bar", NULL };
    ...
if(!PyArg_ParseTupleAndKeywords(args, keywds, ..., kwlist, ...))
    {
        ...bail out

但是,如果我们传递的参数多于两个预期的参数(例如,发出像 whatever(foo="a", bar="b", baz="c") 这样的 python 调用),整个事情就会崩溃(不是真的,它返回一个错误,但这超出了这里的范围)。

我们希望避免这种情况;如果我们能够解析kwlist 中的参数并忽略其他所有内容,那就太好了。最好的方法是什么?

我们正在考虑的一个解决方案是将kwlist 转换为dict,然后使用PyDict_Merge 或类似方法对其进行操作。

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    最后我们解决了如下:

    (我正在回答我自己的问题,因为没有人回答,我认为它将来可能对其他人有价值)。

    PyObject* whatever(PyObject *self, PyObject *args, PyObject *incoming_keywds) 
    {
    
        static char* kwlist[] = { "foo", "bar", NULL };
    
        PyObject* keywds = PyDict_New();
        /**
         * The following routine returns a subset of the incoming dictionary 'incoming_keywds'
         * containing only the keys allowed in the list 'kwlist'
         */
        for ( int i = 0 ; kwlist[i] != NULL ; i++ )
        {
            char* key = kwlist[i];
            PyObject *single_key = Py_BuildValue("s", key);
            if ( PyDict_Contains(incoming_keywds, single_key) )
            {
                // not checking for NULL as GetItem return value since
                // we already checked above if the dict contains key 'single_key'
                if ( PyDict_SetItem(keywds, single_key, PyDict_GetItem(incoming_keywds, single_key)) < 0 )
                {
                    /* error */
                }
            }
            Py_DECREF(single_key);
        }
        /** end */  
    

    【讨论】:

      猜你喜欢
      • 2013-06-17
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多