[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

Example 20-11. PP4E\Integrate\Extend\Cenviron\envattr.py


import os
from cenviron import getenv, putenv # get C module's methods


class EnvWrapper: # wrap in a Python class
def setattr(self, name, value):
os.environ[name] = value # on writes: Env.name=value
putenv(name, value) # put in os.environ too


def getattr(self, name):
value = getenv(name) # on reads: Env.name
os.environ[name] = value # integrity check
return value


Env = EnvWrapper() # make one instance


The following shows our Python wrappers running atop our C extension module’s
functions to access environment variables. The main point to notice here is that you
can graft many different sorts of interface models on top of extension functions by
providing Python wrappers in addition to C extensions:


>>> from envmap import Env
>>> Env['USER']
'skipper'
>>> Env['USER'] = 'professor'
>>> Env['USER']
'professor'
>>>
>>> from envattr import Env
>>> Env.USER
'professor'
>>> Env.USER = 'gilligan'
>>> Env.USER
'gilligan'

Wrapping C Environment Calls with SWIG


You can manually code extension modules like we just did, but you don’t necessarily
have to. Because this example really just wraps functions that already exist in standard
C libraries, the entire cenviron.c C code file in Example 20-8 can be replaced with a
simple SWIG input file that looks like Example 20-12.


Example 20-12. PP4E\Integrate\Extend\Swig\Environ\environ.i


/***



  • Swig module description file, to generate all Python wrapper

  • code for C lib getenv/putenv calls: "swig -python environ.i".
    ***/


%module environ


extern char getenv(const char varname);
extern int putenv(char *assignment);


1500 | Chapter 20: Python/C Integration

Free download pdf