system calls to sh
Donn Cave
donn at u.washington.edu
Fri Mar 17 19:14:57 EST 2000
Quoth "Kia A. Arab" <karab at stsci.edu>:
| I can't seem to affect environment variables using os.system calls. I
| don't know if this makes a difference, but the variables are set in c
| shell. I try to unset them from a python script like so:
|
| os.system('unset MY_VAR')
| os.system('export MY_VAR')
| os.system('echo $MY_VAR') # not unset!
Each system() call forks its own shell process to execute the command,
so each is a sort of miniature script. It modifies its own environment,
and when it exits that environment is forgotten.
I assume your environment variable was inherited from Python, that's
what would happen normally. Python's os.environ allows you to look
at the environment as a dictionary, and you can modify variables and
see the result in the system() -
os.environ['MY_VAR'] = 'new value'
os.system('printenv MY_VAR')
But unfortunately it's kind of hack that synchronizes the environment
with os.environ, changing the former when the latter is changed, and
while you can update a variable, you can't delete one.
If you really want to do it, the system() call is really a pretty
simple wrapper around a few more capable functions.
def esystem(cmd):
pid = os.fork()
if pid:
p, s = os.waitpid(pid, 0)
return (s >> 8) & 0x7f
else:
os.execve('/bin/sh', ('sh', '-c', cmd), os.environ)
os._exit(111)
(Hope I remember that right!) This gives the shell command a copy of
the environment you modify, so deletion works.
Donn Cave, donn at u.washington.edu
More information about the Python-list
mailing list