Macros in Python?

Carl Banks imbosol-1049925772 at aerojockey.com
Wed Apr 9 18:17:53 EDT 2003


Dominic wrote:
> 
> 
> (defmacro with-root-privs (() &body body)
>   (let ((oldidsym (gensym)))
>     `(let ((,oldidsym (geteuid)))
>        (seteuid 0)
>        (unwind-protect
>           (progn , at body)
>         (seteuid ,oldidsym)))))
> 
> Is there an easy way to produce similar code
> in Python which gurantees that certain things
> happen around some code? (Maybe by using
> generators?)
> 
> The normal approach would be to enclose everything
> with try: finally: but this would scatter the
> code all over.


It doesn't have to.  First, define:

    def get_root_privledges():
        euid = os.geteuid()
        os.seteuid(0)
        return euid

    def release_root_privledges(euid):
        os.seteuid(euid)


Then you can do:

    old_euid = get_root_privledges()
    try:
        if x in user:
            active.append(x)
            ...
    finally:
        relase_root_privledges(old_euid)


I hope this isn't what you consider "scattering the code all over."
There is a certain niceness to the with macros (the ones that don't
rebind any symbols, anyways), but try ... finally does the job just
fine.


-- 
CARL BANKS




More information about the Python-list mailing list