Calling all Python experts

Bill Campbell linux-sxs
Wed Dec 20 13:08:01 PST 2006


On Wed, Dec 20, 2006, Michael Hipp wrote:
>David Bandel wrote:
>> Folks,
>> 
>> OK, well, someone took a perfectly good idea originally coded in Perl
>> and decided he liked Python better :-(.
>> 
>> Well, I need to try to figure out how Python handles grabbing
>> arguments to programs.  Specifically, sendmail is calling procmail,
>> which runs a filter in Python (if only this were Perl I could fix it,
>> but I don't feel like learning enough Python to translate the entire
>> program to Perl).
>> 
>> The install suggests something like:
>> "/var/mail/%s" % os.environ.get("USER")
>
>Did a bit more reading on the 'os' module. Turns out this syntax is probably 
>more "correct" and a bit simpler too:
>
>   os.environ['USER']

The problem with doing it this way is that it will raise an
exception if there's no USER envioronment variable.  The syntax
os.environ.get('USER') returns None when there's no matching
environment variable set in the os.environ dictionary (hash in
perl-speak).

One could use this something like this:

user = None
for varname in ('USER', 'LOGNAME'):
	var = os.environ.get(varname)
	if var:
		user = var
		break

if not user:
	raise an error of some kind

One could also use a try/except.

user = None
for varname in ('USER', 'LOGNAME'):
	try:
		var = os.environ[varname]
		break
	except:
		continue

As in perl, there's more than one way to do it.

Bill
--
INTERNET:   bill at Celestial.COM  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676

Basic Definitions of Science:
    If it's green or wiggles, it's biology.
    If it stinks, it's chemistry.
    If it doesn't work, it's physics.



More information about the Linux-users mailing list