[英]Setting Environment Up with Python
Our environment has a shell script to setup the working area. 我们的环境有一个Shell脚本来设置工作区。
setup.sh
looks like this: setup.sh
看起来像这样:
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. 我们的一些用户正在寻找
csh
版本,这意味着拥有两个安装文件。
I'm wondering if there is a way to do this work with a common python file. 我想知道是否有一种方法可以使用常见的python文件来完成这项工作。 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. 在《 The Hitchhiker's Python Guide》中, Kenneth Reitz建议在项目中使用
setup.py
文件,但是我不确定Python是否可以像上面一样在shell中设置环境变量。
Can I replace this shell script with a python script that does the same thing? 我可以用执行相同操作的python脚本替换此shell脚本吗? 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.) (还有其他一些问题用很多评论来更广泛地问这个问题,但是这个问题有一个直接的问题和一个直接的单一答案。)
No, Python (or generally any process on Unix-like platforms) cannot change its parent's environment. 不,Python(或通常在类似Unix的平台上的任何进程)不能更改其父级的环境。
A common solution is to have your script print the output in a format suitable for the user's shell. 常见的解决方案是让脚本以适合用户外壳的格式打印输出。 Eg
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; 例如,
ssh-agent
将使用-s
或与Bourne兼容的shell调用它时,将打印出与sh
兼容的全局分配。 and csh
syntax if invoked from csh
or tcsh
or when explicitly invoked with -c
. 和
csh
语法(如果从csh
或tcsh
调用,或者通过-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. 在
sh
兼容的shell中,通常的调用是$(eval ssh-agent)
,因此程序打印的文本是由用户在其中调用此命令的shell评估的。
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). eval
是一种众所周知的安全风险,因此,即使对于不多说Python(或shell或其他任何东西)的人,您也希望使其易于审核。
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. 如果你是,嗯咳嗽,持怀疑态度的直接支持csh用户,也许你可以说服他们来运行你
sh
在Bourne兼容的shell脚本兼容,然后exec csh
得到他们的首选互动的环境。 This also avoids the slippery slope of having an ever-growing pile of little maintenance challenges for supporting Csh, Fish, rc
, Powershell etc users. 这也避免了越来越多的滑坡,对支持Csh,Fish,
rc
,Powershell等用户的维护挑战很少。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.