to add this code to Python, compile and link into an object file; the Cygwin makefile
in Example 20-9 builds the C source code for dynamic binding on imports.
Example 20-9. PP4E\Integrate\Extend\Cenviron\makefile.cenviron
##################################################################
Compile cenviron.c into cenviron.dll--a shareable object file
on Cygwin, which is loaded dynamically when first imported.
##################################################################
PYLIB = /usr/local/bin
PYINC = /usr/local/include/python3.1
cenviron.dll: cenviron.c
gcc cenviron.c -g -I$(PYINC) -shared -L$(PYLIB) -lpython3.1 -o $@
clean:
rm -f *.pyc cenviron.dll
To build, type make -f makefile.cenviron at your shell. To run, make sure the result-
ing .dll file is in a directory on Python’s module path (the current working directory
works too):
.../PP4E/Integrate/Extend/Cenviron$ python
>>> import cenviron
>>> cenviron.getenv('USER') # like os.environ[key] but refetched
'mark'
>>> cenviron.putenv('USER', 'gilligan') # like os.environ[key]=value
>>> cenviron.getenv('USER') # C sees the changes too
'gilligan'
As before, cenviron is a bona fide Python module object after it is imported, with all
the usual attached information, and errors are raised and reported correctly on errors:
>>> dir(cenviron)
['__doc__', '__file__', '__name__', '__packge__', 'getenv', 'putenv']
>>> cenviron.__file__
'cenviron.dll'
>>> cenviron.__name__
'cenviron'
>>> cenviron.getenv
<built-in function getenv>
>>> cenviron
<module 'cenviron' from 'cenviron.dll'>
>>> cenviron.getenv('HOME')
'/home/mark'
>>> cenviron.getenv('NONESUCH')
SystemError: Error calling getenv
1498 | Chapter 20: Python/C Integration