Environment variables not visible from Python
Thomas Rachel
nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Thu Sep 22 03:21:59 EDT 2011
Am 22.09.2011 08:12 schrieb Steven D'Aprano:
> I don't understand why some environment variables are not visible from
> Python.
>
> [steve at wow-wow ~]$ echo $LINES $COLUMNS $TERM
> 30 140 xterm
> [steve at wow-wow ~]$ python2.6
> Python 2.6.6 (r266:84292, Dec 21 2010, 18:12:50)
> [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import os
>>>> (os.getenv('LINES'), os.getenv('COLUMNS'), os.getenv('TERM'))
> (None, None, 'xterm')
>
They are no environment variables, but merely shell variables.
You can turn them into environment variables with the shell command
"export". After exporting them, they are visible by Python.
The environment can be obtained with env.
So try:
$ python -c 'import os; print "\n".join(sorted("%s=%s" % (k,v) for k,v
in os.environ.iteritems()))' | diff -u - <(env|LANG=C sort)
@@ -61,4 +61,4 @@
XDG_DATA_DIRS=/usr/share
XKEYSYMDB=/usr/share/X11/XKeysymDB
XNLSPATH=/usr/share/X11/nls
-_=/usr/bin/python
+_=/usr/bin/env
and you see that they (nearly) match.
Try as well
$ python -c 'import os; print "\n".join(os.getenv(k) or "" for k in
("LINES","COLUMNS","TERM"))'
linux
$ export LINES
$ python -c 'import os; print "\n".join(os.getenv(k) or "" for k in
("LINES","COLUMNS","TERM"))'
24
linux
$ export COLUMNS
$ python -c 'import os; print "\n".join(os.getenv(k) or "" for k in
("LINES","COLUMNS","TERM"))'
24
80
linux
$
HTH,
Thomas
More information about the Python-list
mailing list