Setting environment variables for tcsh session

David Durkee ddurkee at gmail.com
Fri Jul 22 04:39:01 CEST 2005


Hi,

I'm trying to write a script I can run from tcsh in Terminal (on Mac
OS X) that will set environment variables that can be accessed by
subsequent commands I execute in that session. Not having any luck so
far. Here's what I've tried:

------------
#!/usr/bin/python

import sys
import commands
import os

inputs = sys.argv[1:]
if len(inputs) == 2:
    key = inputs[0]
    val = inputs[1]

    cmd = 'setenv %s "%s"' % (key, val)
    print cmd
    print commands.getstatusoutput(cmd)
    print commands.getoutput('echo $' + key)

-------------
I named the script pysetenv and executed it with the command:

pysetenv TEST "This is a test"

This prints the command in the form I intended, the tcsh setenv
command. When it executes the command, however, it gets an error that
makes it apparent that it is running the command in the sh shell
instead of the tcsh shell I ran it from. So I changed the format of
the command to that used by sh, making the last four lines of my
script:

    cmd = "%s='%s'; export %s" % (key, val, key)
    print cmd
    print commands.getstatusoutput(cmd)
    print commands.getoutput('echo $' + key)

For this one it was apparent that the command did not get an error,
but the echo was still echoing an old value of the variable.

So I replaced the last four lines with this:

    os.environ[key] = val
    print commands.getoutput('echo $' + key)

In this case, the echo command printed the value of the variable I had
just set! Success, or so I thought. However, a subsequent echo command
from the command prompt still returned the old value of the variable.
I think running the script must start a new session and that variables
set in that session are only current as long as the script is running.

Any ideas?

David



More information about the Python-list mailing list