Python C API Usage details (ii)

Source: Internet
Author: User
Tags python list

Brief introduction

This article introduces the use of lists, tuples and dictionaries in the Python C API, and introduces the methods in the API in detail.

Python List API

List API Brief Introduction

int Pylist_check (Pyobject *p) determines whether it is a Python list (list)

pyobject* pylist_new (py_ssize_t len) Create a list

py_ssize_t pylist_size (Pyobject *list) Gets the number of list elements len (list)

py_ssize_t pylist_get_size (Pyobject *list) and pylist_size, but there is no error checking

Pyobject pylist_getitem (pyobject list, py_ssize_t index) gets an element from the list, and the counter does not add 1

Pyobject pylist_get_item (pyobject list, py_ssize_t i) and pylist_getitem, but there is no error checking

int Pylist_setitem (pyobject list, py_ssize_t index, Pyobject Item) Sets the value of the table at the specified position, where the subscript must be of a value and is valid

void Pylist_set_item (Pyobject list, py_ssize_t i, Pyobject o) and Pylist_setitem, but there is no error checking

int Pylist_insert (pyobject list, py_ssize_t index, Pyobject Item) Inserts a value at the specified position in the list List.insert (index, item)

int pylist_append (pyobject list, Pyobject item) appends a value list.append (item) at the end of the list

Pyobject pylist_getslice (pyobject list, py_ssize_t Low, py_ssize_t high) gets a slice of data from the list, a specified range of data list[low:higt ]

int Pylist_setslice (pyobject list , py_ssize_t Low, py_ssize_t High, Pyobject itemlist) sets the list shard data, specifying the list range of data list[ Low:higt] = itemlist

int Pylist_sort (Pyobject *list) Sorts the list data list.sort ()

int Pylist_reverse (Pyobject *list) reverses all the data inside the list List.reverse ()

Pyobject pylist_astuple (pyobject list) Convert Python list to Python tuple tuple (list)

Instance

Caveats: Python list objects that are not limited in size should be initialized with append data

Set the size of the Python list object, you should initialize the data with SetItem, if you use Append, there will be "segment error (Core dump)" situation

Header file

//// Created by lanyulei on 18-9-3.//#ifndef PRINT_DEMO1_PYLIST_H#define PRINT_DEMO1_PYLIST_H#include <Python.h>#include "print.h"// 创建一个固定大小的列表void ListNumber();// 创建一个可以无限扩展的列表void ListExpansion();#endif //PRINT_DEMO1_PYLIST_H

source file

Created by Lanyulei on 18-9-3.//#include <stdio.h> #include <stdlib.h> #include <string.h>#    Include "pyList.h"//A list with a length limit of void Listnumber () {pyobject* pylist = pylist_new (3);   Create a list with a size of 3 pyobject* Pyid = Py_buildvalue ("I", 123);   Create a Python integer object Pylist_setitem (pylist, 0, Pyid);   Inserts a python integer object into a Python list object pyobject* pyname = Py_buildvalue ("s", "Lanyulei");   Create a String Python object Pylist_setitem (pylist, 1, pyname);   Insert into Python list object go to pyobject* pyfloat = Py_buildvalue ("f", 23.98f);   Create a Python object of floating-point type Pylist_setitem (Pylist, 2, pyfloat);   Insert it into the Python list object int listlength = Pylist_size (pylist);    Gets the length of the list printf ("List length:%d\n", listlength);    Print_pyobject (pylist);  Print List data pyobject* pyName2 = Py_buildvalue ("s", "Lanyulei");   Create a String Python object Pylist_insert (pylist, 1, pyName2);    Insert a Data print_pyobject (pylist) at the position labeled 1;    Print List data printf ("------------sort-------------\ n");    Pylist_sort (pylist); On the listTo sort Print_pyobject (pylist);    Print List data printf ("---------------reverse--------------\ n");    Pylist_reverse (pylist);    Reverse list Data print_pyobject (pylist);    Print List data printf ("----------------slice----------------\ n");   pyobject* Pyslice = Pylist_getslice (pylist, 1, 3);    Gets the Shard data print_pyobject (Pyslice);    Print Shard data}//No size limit for the list void Listexpansion () {pyobject* pylist = pylist_new (0);   Create a list with no size limit, so the parameter is 0 pyobject* Pyid = py_buildvalue ("I", 123);   Create a Python integer object Pylist_append (Pylist, Pyid);   Appends a Python integer object to a Python list object pyobject* pyname = Py_buildvalue ("s", "Lanyulei");   Create a String Python object Pylist_append (Pylist, pyname);   Append to Python list object go to pyobject* pyfloat = Py_buildvalue ("f", 23.98f);   Create a Python object of floating-point type Pylist_append (Pylist, pyfloat);    Append it to the Python list Object Print_pyobject (pylist);   pyobject* py_data = Pylist_getitem (pylist, 0); Gets the data print_pyobject (Py_data) labeled 0;}
Python Tuple API

A simple introduction to the Tuple API

int Pytuple_check (Pyobject *p) determines if it is a tuple object

pyobject* pytuple_new (py_ssize_t len) creates a Python tuple object, noting that tuple creation must be set length, and if the set length is 0, the tuple object is an empty tuple

py_ssize_t pytuple_size (Pyobject *p) Gets the length of the tuple, which is the size of the tuple

py_ssize_t pytuple_get_size (Pyobject *p) and pytuple_size, except that this method does not have a mechanism for error checking

Pyobject pytuple_getitem (Pyobject p, py_ssize_t POS) Gets the value of the specified underlying in the tuple

Pyobject pytuple_get_item (Pyobject p, py_ssize_t POS) and Pytuple_getitem, except that this method does not have a mechanism for error checking

Pyobject pytuple_getslice (Pyobject p, py_ssize_t Low, py_ssize_t high) Get Shard data p[lwo, Higt]

int Pytuple_setitem (Pyobject p, py_ssize_t pos, Pyobject o) sets a tuple to specify the value of the underlying

void Pytuple_set_item (Pyobject p, py_ssize_t pos, Pyobject o) and Pytuple_setitem, except that this method does not have a mechanism for error checking

int _pytuple_resize (Pyobject **p, py_ssize_t newsize) Change the size of the tuple

Instance

Header file

//// Created by lanyulei on 18-9-4.//#ifndef PRINT_DEMO1_PYTUPLE_H#define PRINT_DEMO1_PYTUPLE_H#include <Python.h>#include <string.h>#include <stdio.h>#include <stdlib.h>#include "print.h"// 元组的使用void test_tuple();#endif //PRINT_DEMO1_PYTUPLE_H

source file

Created by Lanyulei on 18-9-4.//#include "pyTuple.h" void Test_tuple () {pyobject* pytuple = pytuple_new (3);   Create a tuple pyobject* Pyid = Py_buildvalue ("i", 1);   Create a Python integer object Pytuple_setitem (pytuple, 0, Pyid);   Passes data to the specified subscript pyobject* pystring = Py_buildvalue ("s", "Lanyulei");    Create a Python string Object Pytuple_setitem (Pytuple, 1, pystring);    pyobject* pyfloat = Py_buildvalue ("f", 165.46f);    Create a Python floating-point object Pytuple_setitem (Pytuple, 2, pyfloat);    int tuplelength = pytuple_size (pytuple);    printf ("Pytuple Size:%d\n", tuplelength);    Print_pyobject (pytuple);    printf ("----------------------Pytuple_getitem--------------------------\ n");   pyobject* pydata = Pytuple_getitem (pytuple, 0);    Gets the tuple-specified subscript data print_pyobject (pydata);    printf ("------------------------traversal tuple--------------------------\ n");        Traverse the tuple data for (int i = 0; i < pytuple_size (pytuple); i++) {pyobject* pydata = Pytuple_getitem (pytuple, i);    Print_pyobject (Pydata); }   printf ("------------------------get shard data--------------------------\ n");   pyobject* Pyslice = Pytuple_getslice (pytuple, 1, pytuple_size (pytuple));    Get Slice Data print_pyobject (pyslice);    printf ("------------------------modify tuple length--------------------------\ n");    printf ("Original length:%d\n", tuplelength);   _pytuple_resize (&pytuple, 5); To modify the tuple length, the first parameter is a pointer to printf ("Resize tuple length:%ld\n", Pytuple_size (Pytuple));}
Python Dict API

Dict API Brief Introduction

int Pydict_check (Pyobject *p) determines whether an object is not a dictionary

pyobject* pydict_new () Create a Python object

void Pydict_clear (Pyobject *p) empties data from a Python object

int Pydict_contains (Pyobject p, pyobject key) determines if a key value data exists in the dictionary

Pyobject pydict_copy (pyobject p) copies data from a dictionary, producing a new Python Dictionary object

int Pydict_setitem (Pyobject p, pyobject key, Pyobject *val) sets new key-value data for Python Dictionary objects

int pydict_setitemstring (Pyobject p, const char key, Pyobject *val) is similar to Pydict_setitem except that the key is a C-language char data type data

int Pydict_delitem (Pyobject p, pyobject key) deletes Python key value data

int pydict_delitemstring (Pyobject p, const char key) is similar to Pydict_delitem, except that the key is the C language Char data type data

Pyobject pydict_getitem (Pyobject p, Pyobject *key) Gets the value of the key of the Python Dictionary object

Pyobject pydict_getitemwitherror (Pyobject p, pyobject *key) and Pydict_getitem, just return the context of the error message

Pyobject pydict_getitemstring (pyobject p, const char *key) and Pydict_getitem, only data of the char data type in the key-value C language

Pyobject pydict_setdefault (Pyobject p, pyobject key, Pyobject default) sets the defaults for the Python Dictionary object, Returns the current default data when the acquired key does not exist Dict.setdefault ()

Pyobject pydict_items (pyobject p) returns the pylistobject of all data for a Python Dictionary object, Dict.items ()

Pyobject Pydict_keys (pyobject p) returns all key data for a Python Dictionary object Dict.keys ()

Pyobject pydict_values (pyobject p) Returns all value data for a Python Dictionary object Dict.values ()

py_ssize_t pydict_size (Pyobject *p) Gets the size of the Python dictionary len (dict)

int Pydict_next (Pyobject p, py_ssize_t PPOs, Pyobject pkey, Pyobject pvalue) traverses all the data that gets the Python Dictionary object, Here is an example of what is officially provided

PyObject *key, *value;Py_ssize_t pos = 0;   // 初始值必须为0, 表示遍历所有Python字典对象数据while (PyDict_Next(self->dict, &pos, &key, &value)) {    /* do something interesting with the values... */    ...}PyObject *key, *value;Py_ssize_t pos = 0;while (PyDict_Next(self->dict, &pos, &key, &value)) {    long i = PyLong_AsLong(value);    if (i == -1 && PyErr_Occurred()) {        return -1;    }    PyObject *o = PyLong_FromLong(i + 1);    if (o == NULL)        return -1;    if (PyDict_SetItem(self->dict, key, o) < 0) {        Py_DECREF(o);        return -1;    }    Py_DECREF(o);}

int Pydict_merge (Pyobject A, pyobject b, int override) adds the data in the B dictionary to the A dictionary, and override indicates whether the data is overwritten, Overwrite data if override is true and vice versa

int Pydict_update (Pyobject A, pyobject b) Adds the data in the B dictionary to the A dictionary, and b directly updates the value of the key in a if the same key appears in A and b

Instance

Header file

//// Created by lanyulei on 18-9-5.//#ifndef PRINT_DEMO1_PYDCIT_H#define PRINT_DEMO1_PYDCIT_H#include <stdio.h>#include <stdlib.h>#include <string.h>#include <Python.h>#include "print.h"// 字典练习void test_dict();#endif //PRINT_DEMO1_PYDCIT_H

source file

Created by Lanyulei on 18-9-5.//#include "pyDcit.h" void Test_dict () {//create dict pyobject* py_dict_1 = pydict_new (    );    Check that Pyobject is not a dictionary int ret = Pydict_check (py_dict_1);    if (ret) {printf ("is dict\n");    } else {printf ("is not dict\n");    } pyobject *py_key_account_id = Py_buildvalue ("s", "account_id");    Pyobject *py_value_account_id = Py_buildvalue ("i", 1238);    Add a Key-value pydict_setitem (py_dict_1, py_key_account_id, py_value_account_id) to Dict;    Pyobject *py_value_account_name = Py_buildvalue ("s", "mono");    Pydict_setitemstring (py_dict_1, "account_name", py_value_account_name);    Pyobject *py_key1 = Py_buildvalue ("i", 1);    Pyobject *py_key1_value = Py_buildvalue ("i", 2399);    Pydict_setitem (py_dict_1, Py_key1, Py_key1_value);    Gets the size of the dictionary int dict_len = pydict_size (py_dict_1);    printf ("dict_len=%d\n", Dict_len);    Print_pyobject (py_dict_1);    Delete a key Pydict_delitem (Py_dict_1, py_key_account_id) from the dictionary; Printf("del item:py_key_account_id--------------------------\ n");    Print_pyobject (py_dict_1);    Delete a nonexistent key pyobject *py_not_existing_key = Py_buildvalue ("s", "name");    Pydict_delitem (py_dict_1, Py_not_existing_key);    printf ("del item:py_not_existing_key------------------\ n");    Print_pyobject (py_dict_1);    -------------------------------------------------------//pydict_delitemstring (py_dict_1, "account_name");    printf ("del item:account_name-----------------\ n");    Print_pyobject (py_dict_1);    Pyobject *py_key_account_name = Py_buildvalue ("s", "account_name");    Get a key-value pyobject *py_value1 = Pydict_getitem (py_dict_1, py_key_account_name) from the dictionary;    printf ("Get item:account_name-----------------------\ n");    Print_pyobject (py_value1);    printf ("\ n");    Get a key-value pyobject *py_value2 = pydict_getitemstring (py_dict_1, "account_name") from the dictionary;    printf ("Get item String:account_name-------------------\ n");    Print_pyobject (py_value2); Printf("\ n"); -----------------------------------------------------------//Get all Key-value from the dictionary to pyobject *py_items = Pydict_item    S (py_dict_1);    printf ("Get items--------------------------\ n");    Print_pyobject (Py_items);    printf ("\ n");    --------------------------------------//Get all key pyobject *py_keys = Pydict_keys (py_dict_1) from the dictionary;    printf ("Get keys-------------------------\ n");    Print_pyobject (Py_keys);    printf ("\ n");    ------------------------------------------------//Get all values from the dictionary pyobject *py_values = pydict_values (py_dict_1);    printf ("Get values-----------------------\ n");    Print_pyobject (py_values);    printf ("\ n");    ------------------------------------------------------//Traverse dictionary pyobject *key, *value;    py_ssize_t pos = 0;    printf ("Dict next-------------------\ n");        while (Pydict_next (py_dict_1, &pos, &key, &value)) {print_pyobject (key);        printf ("=");        Print_pyobject (value); printf ("\ n");    }//---------------------------------------------pyobject *py_dict_2 = Pydict_new ();    Pyobject *py_key21 = Py_buildvalue ("I", 101);    Pyobject *py_key21_value = Py_buildvalue ("i", 60000);    Pydict_setitem (Py_dict_2, Py_key21, Py_key21_value);    Pyobject *py_value_level = Py_buildvalue ("i", 30);    Pydict_setitemstring (py_dict_2, "Account_level", py_value_level);    Pyobject *py_value_account_name2 = Py_buildvalue ("s", "myname");    Pydict_setitemstring (py_dict_2, "account_name", py_value_account_name2);    printf ("Dict_2 items--------------------\ n");    Print_pyobject (py_dict_2);    Add all py_dict_2 data to Py_dict_1 pydict_merge (py_dict_1, py_dict_2, 0);    printf ("Dict merge:override=0,-----------------\ n");    Print_pyobject (py_dict_1);    ----------------------------------------Pyobject *py_dict_3 = Pydict_new ();    Pyobject *py_value_score = Py_buildvalue ("I", 10000);    Pydict_setitemstring (Py_dict_3, "Account_score", Py_value_score); Pyobject *py_value_account_name3 = Py_buildvalue ("s", "Sujin");    Pydict_setitemstring (Py_dict_3, "account_name", Py_value_account_name3);    Add all py_dict_3 data to py_dict_1, which is equivalent to the pydict_merge third parameter of 1.    Pydict_update (py_dict_1, py_dict_3);    printf ("Dict update----------------------\ n");    Print_pyobject (py_dict_1);    ---------------------------------------------const char *check_key = "account_name";    Pyobject *py_check_key = Py_buildvalue ("s", Check_key);    Check the dictionary for the existence of this key ret = Pydict_contains (py_dict_3, Py_check_key);    if (ret) {printf ("has key:%s\n", Check_key);    } else {printf ("No Key:%s\n", Check_key);    }//-------------------------------------------------//Empty the dictionary for all data pydict_clear (py_dict_3);    printf ("Dict clear---------------------\ n"); Print_pyobject (py_dict_3);}
Methods for printing data based on data type

Header file

//// Created by lanyulei on 18-9-1.//#ifndef PRINT_DEMO1_PRINT_H#define PRINT_DEMO1_PRINT_H#include <Python.h>void print_pyobject(PyObject *py_obj);#endif //PRINT_DEMO1_PRINT_H

source file

Created by Lanyulei on 18-9-1.//#include "print.h" #include <stdio.h> #include <string.h> #include < stdlib.h>//floating-point type in Python, all doublevoid print_pyobject (Pyobject *py_obj) {if (py_obj = = null) {printf ("null")        ;    Return        } if (Pyint_check (py_obj)) {//int int ival = Pyint_aslong (py_obj);    printf ("I am integral type, ival =%d\n", ival);        } else if (Pylong_check (py_obj)) {//Long long lval = Pylong_aslonglong (py_obj);    printf ("I am a long integer, lval =%lld\n", lval);        } else if (Pyfloat_check (py_obj)) {//float/double double fval = pyfloat_as_double (py_obj);    printf ("I am a floating-point type, fval =%lf\n", fval);        } else if (Pybool_check (py_obj)) {//bool int bval = Pyint_aslong (py_obj);        if (bval = = 1) {printf ("I am a Boolean type, Bval = true\n");        }else {printf ("I am a Boolean type, Bval = false\n"); }} else if (Pystring_check (py_obj)) {//Does not contain Chinese string char *str = pystring_asString (Py_obj);    printf ("I am a string that does not contain Chinese, str =%s\n", str); } else if (Pyunicode_check (py_obj)) {//Unicode contains Chinese strings//first converts Unicode to utf-8 pyobject *py_utf8 = Pyu        Nicode_asutf8string (Py_obj);        Char *ustr = pystring_asstring (Py_utf8);    printf ("I am unicode,ustr =%s\n", USTR);        } else if (Pylist_check (py_obj)) {//Python list printf ("I am a list,");        printf ("[\ n");            for (int i = 0;i < Pylist_size (py_obj); i++) {Pyobject *py_data = Pylist_getitem (py_obj, i);        Print_pyobject (Py_data);    } printf ("]\n");        } else if (Pytuple_check (py_obj)) {//Python tuple printf ("I am a tuple,");        printf ("(\ n");            for (int i = 0;i < Pytuple_size (py_obj); i++) {Pyobject *py_data = Pytuple_getitem (py_obj, i);        Print_pyobject (Py_data);    } printf (") \ n");        } else if (Pydict_check (py_obj)) {//Python dict pyobject *key, *value; py_ssize_t pos = 0;        printf ("I Am a dictionary,");        printf ("{\ n");            while (Pydict_next (Py_obj, &pos, &key, &value)) {print_pyobject (key);            printf ("=");        Print_pyobject (value);    } printf ("}\n"); }}

Main function

#include <stdio.h>#include <stdlib.h>#include <string.h>int main() {    // 初始化Python虚拟机    Py_Initialize();    // 判断Python虚拟机是否成功    if (Py_IsInitialized() == 0){        printf("fal to initialize Python\n");        return -1;    }    printf("server start\n");    // 退出Python虚拟机    Py_Finalize();    return 0;}

Python C API Usage details (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.