Macros in Python?
Dominic
oblivious at web.de
Thu Apr 10 05:57:04 EDT 2003
Carl Banks wrote:
> 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.
This solution is very straightforward but I have been curious wether
there is a "nicer" way to do the job. Alexander and Jp's postings
showed me that there are two very different approaches which could
also be used. Certainly all 3 solutions have their pros and cons
I'll consider all three.
So, thank you very much for all your answers :)
Ciao,
Dominic
P.S. It would be nice to have a database for python usage patterns.
>
>
More information about the Python-list
mailing list