用Python替换C代码
A Python Successful Story

Adieu
Oct 21, 2011

About Me

Why?

I don’t think necessity is the mother of invention – invention, in my opinion, arises directly from idleness, possibly also from laziness. To save oneself trouble.
Agatha Christie

How?

替换C程序

tinyproxy

使用C开发的小型多进程Proxy

tproxy + Python Script

基于Gevent的单进程Proxy

def proxy(data):
    recved = len(data)
    parser = HttpParser()
    parsed = parser.execute(data, recved)
    if parsed != recved:
        return  { 'close':'HTTP/1.0 502 Gateway Error\r\n\r\nError parsing request'}

    if not parser.get_url():
        return

    parsed_url = urlparse.urlparse(parser.get_url())
    is_ssl = parsed_url.scheme == "https"
    remote = parse_address(parser.get_headers()['Host'], 80)

    return {"remote": remote, 
            "ssl": is_ssl}
Source: https://github.com/benoitc/tproxy/blob/master/examples/httpproxy.py

替换C插件

pppd与openvpn认证插件开发

def chap_check():
    return 1

def chap_verify(username, ourname, id, challenge, response, message, message_space):
    result = client.chap_auth(username, base64.encodestring(challenge), base64.encodestring(response))
    if result:
        if result['result']:
            result['password_hash_hash'] = base64.decodestring(result['password_hash_hash'])
            result['client_ip'] = long(result['client_ip'])
            return result
        else:
            return result
    else:
        return {'result': 0}

替换C函数调用

libnfc + swig

from nfc._nfc import *

pnd = nfc_connect(None)
nfc_initiator_init(pnd)

nfc_configure (pnd, NDO_ACTIVATE_FIELD, False)
nfc_configure (pnd, NDO_HANDLE_CRC, False)
nfc_configure (pnd, NDO_HANDLE_PARITY, True)
nfc_configure (pnd, NDO_EASY_FRAMING, False)
nfc_configure (pnd, NDO_ACTIVATE_FIELD, True)

abtReqa = bytearray(b'\x26')
result = nfc_initiator_transceive_bits(pnd, abtReqa,7)
print repr(result)

abtSelectAll = bytearray(b'\x93\x20')
result = nfc_initiator_transceive_bytes(pnd, abtSelectAll, None)
print repr(result)

abtSelect = bytearray(b'\x93\x70') + result
abtSelect = abtSelect + iso14443a_crc(abtSelect)
result = nfc_initiator_transceive_bytes(pnd, abtSelect, None)
print repr(result)

abtHalt = bytearray(b'\x50\x00\x57\xCD')
result = nfc_initiator_transceive_bytes(pnd, abtHalt, None)
print repr(result)

One more thing...

One More Thing

替换C源代码

RPython

In common parlance, PyPy has been used to mean two things. The first is the RPython translation toolchain, which is a framework for generating dynamic programming language implementations. And the second is one particular implementation that is so generated – an implementation of the Python programming language written in Python itself. It is designed to be flexible and easy to experiment with.
This double usage has proven to be confusing, and we are trying to move away from using the word PyPy to mean both things. From now on we will try to use PyPy to only mean the Python implementation, and say the RPython translation toolchain when we mean the framework.

PyPy Documentation

rpythonic

import os, sys, time
sys.path.append('..')
import rpythonic
rpythonic.set_pypy_root( '../../pypy' )
rpythonic.set_android_sdk_root( '../../android-sdk-linux_x86/' )
rpythonic.set_android_ndk_root( '../../android-ndk-r5b/' )
rpy = rpythonic.RPython('android')

@rpy.standalone
def main():
        rpy.setup_display()


package = rpy.compile()
print( package.apk )
Source: http://code.google.com/p/rpythonic/source/browse/examples-android/android_helloworld.py

Conclusion

谢谢

相关链接

Slides地址