开发者

problem with python script

I want to run a csh file from a python script,

example,

#!/usr/bin/python
import os

os.system("source path/to/file.csh")

and I want this file to开发者_开发问答 run in the same shell as I am running the python script, because the file.csh script is settings some environment variables that I need.

Does anyone know how to do this in Python?


A child process cannot affect the environment of the parent process. The best you can do is to run your csh script in a separate process, get the environment variables that it defines, then set each environment variable in your python script.

Even with that, the python script won't be able to affect the shell in which you run the python script.

The common way to solve this (AFAIK) is to have your script emit shell commands to set the environment, then from the main shell you run the script and eval what you get back.

For more information you might want to check out this question: can a shell script set environment variables of the calling shell


You can kludge it this way:

#!/usr/bin/env python
# This is kludge.py

print "setenv VARNAME \"the value\""

In your case, you can have the file.sh print the setenv line.

Then from csh:

$ eval `./kludge.py`
$ echo $VARNAME 
the value

This isn't clean, but it is the only way to have a child process effect the environment of its parent. This is only because the parent process is explicitly letting it happen with eval.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜