0

Our environment has a shell script to setup the working area. setup.sh looks like this:

 export BASE_DIR=$PWD
 export PATH=$BASE_DIR/bin
 export THIS_VARIABLE=THAT_VALUE

The user does the following:

 % . setup.sh

Some of our users are looking for a csh version and that would mean having two setup files.

I'm wondering if there is a way to do this work with a common python file. In The Hitchhiker's Guide to Python Kenneth Reitz suggests using a setup.py file in projects, but I'm not sure if Python can set environment variables in the shell as I do above.

Can I replace this shell script with a python script that does the same thing? I don't see how.

(There are other questions that ask this more broadly with many many comments, but this one has a direct question and direct single answer.)

Ray Salemi
  • 5,247
  • 4
  • 30
  • 63
  • Possible duplicate of [Why can't environmental variables set in python persist?](https://stackoverflow.com/questions/716011/why-cant-environmental-variables-set-in-python-persist) – Tom de Geus Mar 15 '18 at 13:21

1 Answers1

3

No, Python (or generally any process on Unix-like platforms) cannot change its parent's environment.

A common solution is to have your script print the output in a format suitable for the user's shell. E.g. ssh-agent will print out sh-compatible global assignments with -s or when it sees that it is being invoked from a Bourne-compatible shell; and csh syntax if invoked from csh or tcsh or when explicitly invoked with -c.

The usual invocation in sh-compatible shells is $(eval ssh-agent) -- so the text that the program prints is evaluated by the shell where the user invoked this command.

eval is a well-known security risk, so you want to make this code very easy to vet even for people who don't speak much Python (or shell, or anything much else).

If you are, eh cough, skeptical of directly supporting Csh users, perhaps you can convince them to run your sh-compatible script in a Bourne-compatible shell and then exec csh to get their preferred interactive environment. This also avoids the slippery slope of having an ever-growing pile of little maintenance challenges for supporting Csh, Fish, rc, Powershell etc users.

tripleee
  • 175,061
  • 34
  • 275
  • 318