[Original] using C language to expand Python

Source: Internet
Author: User
Tags prefetch

We know that python is a scripting language with many advantages such as high development speed, but there are some differences in execution efficiency. How can we take into account the development speed and execution efficiency.
In fact, Python can be easily extended using the C language. Let's take a look at it.

Here we implement a python extension that uses libcurl to request a webpage.

First, we need Python. h to directly install python-devel on RHEL.
Create a file named httpmodule. c.
After opening, write the following code:

#include <Python.h><stdio.h><curl/curl.h>

Then write the execution function

 PyObject **self,PyObject **==     (res != Py_BuildValue(

This function has a fixed pattern

 PyObject **self,PyObject *args)

Then write the export Function

 PyMethodDef httpMethods[]=,http_get,METH_VARARGS, 

Then the module initialization Function


Then we can compile it.
Run the following command:

Gcc-fpic-c-I/usr/include/python2.6/httpmodule. c
Gcc -- shared-o http. so httpmodule. o-lcurl

Then we enter the python interaction mode.

>>> Import http
>>> Dir (http)
['_ Doc _', '_ file _', '_ name _', '_ package _', 'get']
>>> Http. get ()
<! DOCTYPE html> <! -- Status OK -->
So far, we have successfully compiled the python C extension.

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.