os.environ and os.path.chdir

Thomas Bellman bellman at lysator.liu.se
Sat Sep 20 16:07:17 EDT 2003


Geoff Gerrietts <geoff at gerrietts.net> wrote:

> Quoting Yun Mao (maoy at cis.upenn.edu):
>> Hi,
>>    How to make changes to os.environ and os.path.chdir still effective after
>> I run the script? Currently, the changes are only good within my script. I
>> would like the shell who called python myprog.py also gets the change..
>> Thank you!

> To the best of my knowledge, this can't be done.
[...]
>As far as I know, though, there's no way to actually hijack the user's
>shell process. The user needs to explicitly give you that control.

Actually, there are a couple of ways to do it, at least under
Unix.  However, they have their problems...

One way is to stuff characters into the terminals input buffer
using the TIOCSTI ioctl.  Like this:

    import fcntl, termios
    for c in "cd /usr/lib\n":
	fcntl.ioctl(1, termios.TIOCSTI, c)

It only works if it is being run interctively, under a tty,
though.  If you have a shell script running the above program,
the shell script won't see the command, and thus won't change
directory.  It will be the original shell that gets the command.
And if you're not on a tty, it doesn't work at all.

Also, the command you stuff into the terminal can get mixed up
with normal type-ahead typed by the user, leaving some garbled
command for the shell to read.

So, it's not very reliable.


Another way is to attach a debugger to the parent process, and
force it to do the chdir() system call, or poke around in its
memory to change the environment variables.  Like this:

    import os
    gdb = os.popen('gdb $SHELL %d' % (os.getppid(),), 'w')
    gdb.write('call chdir("/usr/lib")\n')
    gdb.write('detach\n')
    gdb.write('quit\n')
    gdb.close()

Untested code, but you probably get the idea.

Changing the environment variables of the parent is a bit
trickier.  You need to know the memory layout of the parent,
so you can poke the correct bytes.  You might be able to locate
the variable 'environ' and follow it, but there is no guarantee
it is still pointing to anything useful.


However, I would recommend *against* both of these methods.
Don't try any of this stuff youselves, kids; always get a parent
to supervise this kind of experiments! :-)


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"The one who says it cannot be done should    ! bellman @ lysator.liu.se
 never interrupt the one who is doing it."    ! Make Love -- Nicht Wahr!




More information about the Python-list mailing list