environment variable issue

Tim Chase python.list at tim.thechases.com
Mon Sep 15 21:09:21 CEST 2008


> Could someone explain me what I'm doing wrong here? I'm trying to 
> retrieve the value of an environment variable in Ubuntu 8.04 like this:
> 
>  >>> import os
>  >>> os.environ['USER']
> 'michel'
> 
> This works but this doesn't:
> 
>  >>> os.environ['HOSTNAME']
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
>    File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__
>      raise KeyError(key)
> KeyError: 'HOSTNAME'
> 
> Why is it working in the first case but not in the second one. I must be 
> missing something but it seems I'm not able to figure it out.

This is likely the same issue I just posted about here:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/42346439533bd23a

Your HOSTNAME variable hasn't been exported to subshells.  You 
can check this by looking at the output of

   bash$ export -p

which will print all the variables that are exported.  I suspect 
you'll see $USER in the list, but not $HOSTNAME

However, for the hostname, you might be interested in

   >>> import platform as p
   >>> p.uname()[1]
   'rubbish'

which does this in a cross-platform way without needing to fuss 
with exporting environment variables.

-tkc







More information about the Python-list mailing list