From: Greg Ercolano <erco@(email surpressed)>
Subject: Re: Using Rush in a slightly different way [for Framecycler]
   Date: Tue, 20 Sep 2005 14:40:34 -0700
Msg# 1041
View Complete Thread (3 articles) | All Threads
Last Next
For instance, to load a csh environment into perl, this simple
bit of magic spawns a csh to load the settings, then prints them
out in a format that perl can read back and load into its own environment:

# LOAD A CSH SCRIPT'S ENVIRONMENT SETTINGS INTO PERL ENVIRONMENT
#    $1 = csh script to be 'sourced'
#    Returns: $ENV{} modified as per csh script's settings.
#
sub LoadEnvFromCsh()
{
    my ($rcfile) = @_;
    my $vars = `csh -fc 'source $rcfile; printenv'`;
    foreach ( split(/\n/, $vars) )
        { if ( /(^[^=]*)=(.*)/ ) { $ENV{$1} = $2; } }
}

    I'm sure a similar technique can be done in python.

    In a true re-enactment of the blind leading the blind,
    here's a stab at the python equivalent:

--- snip

import os

# LOAD CSH ENVIRONMENT SETTINGS INTO THE CURRENT PYTHON ENVIRONMENT
#    file -- csh script to be 'sourced'
#    Returns: os.environ[] modifed as per csh script's settings
#
def LoadCSHEnvironment(file):
    fp = os.popen("csh -fc 'source "+file+"; printenv'", "r")
    for line in fp.xreadlines():
        line = line.replace("\n","")            # foo=bar\n -> foo=bar
        x = line.find("=")
        var = line[:x]                          # foo=bar -> foo
        val = line[(x+1):]                      # foo=bar -> bar
        os.environ[var] = val                   # set environment variable
    fp.close()

--- snip

    There's probably a way to make that a few lines shorter;
    I'm not too familiar with Python's string manipulation yet.

    Usage of the above might be, for instance:

--- snip

print "--- BEFORE:"
for var in os.environ:
    print "os.environ['%s'] = '%s'" % (var, os.environ[var])

LoadCSHEnvironment("/net/erco/.cshrc")

print "--- AFTER:"
for var in os.environ:
    print "os.environ['%s'] = '%s'" % (var, os.environ[var])

--- snip

Last Next