Calling the source command from subprocess.popen to update the os.environ.

Chris Angelico rosuav at gmail.com
Sun Mar 27 10:34:06 EDT 2016


On Mon, Mar 28, 2016 at 12:24 AM, Hongyi Zhao <hongyi.zhao at gmail.com> wrote:
> # replace env
> os.environ.clear()
> os.environ.update(line.partition('=')[::2] for line in output.split('\0'))
>
> Traceback (most recent call last):
>   File "/home/werner/anaconda2/lib/python2.7/site-packages/IPython/core/
> interactiveshell.py", line 3066, in run_code
>     exec(code_obj, self.user_global_ns, self.user_ns)
>   File "<ipython-input-24-816c472b62f2>", line 10, in <module>
>     os.environ.clear()
>   File "/home/werner/anaconda2/lib/python2.7/os.py", line 501, in clear
>     unsetenv(key)
> OSError: [Errno 22] Invalid argument
>
> If I don't use the `os.environ.clear()' code line, it will work smoothly.

Do you need to clear the environment first? Anything that's been
overwritten will replace stuff in os.environ, so the only reason to
clear it would be if you expect your env script to unset things. Is
that the case?

I'm not sure why the clear is a problem. Here's how I'd start debugging it:

for var in os.environ:
    try: del os.environ[var]
    except OSError: print(var)

Two possibilities: Either that raises OSError errno 22, same as
clear() does; or it doesn't. If it doesn't, you should have a clear
env, and all should be working (if a little odd) - and then you can
look into the possible bug with clear(). But more likely it will, and
then you'll be able to see exactly which key triggered the error.
Check out what that key is; maybe there's some kind of special
environment variable that can't be cleared??

Worst case, you can always do this "clear whatever you can", and then
do your environ.update(). Assuming you never need to clear one of the
unclearables, this'll give you the same env update as sourcing the
script did.

And worst worst case, you could probably exec to bash, source the
script, and exec back into Python. That should properly update the
environment, but it's a somewhat hamfisted way to go about it :)

ChrisA



More information about the Python-list mailing list