为什么python中设置的环境变量不能持久化?
问题描述
我希望编写一个 python 脚本来创建一些适当的环境变量,方法是在我将要执行一些模拟代码的任何目录中运行该脚本,并且我读到我无法编写脚本来制作这些环境vars 保留在 mac os 终端中.所以两件事:
I was hoping to write a python script to create some appropriate environmental variables by running the script in whatever directory I'll be executing some simulation code, and I've read that I can't write a script to make these env vars persist in the mac os terminal. So two things:
这是真的吗?
和
这似乎是一件有用的事情;为什么一般来说不可能?
It seems like it would be a useful things to do; why isn't it possible in general?
解决方案
你不能从 python 中做到这一点,但是一些聪明的 bash 技巧可以做类似的事情.基本推理是这样的:环境变量存在于每个进程的内存空间中.当使用 fork() 创建一个新进程时,它会继承其父进程的环境变量.当您像这样在 shell(例如 bash)中设置环境变量时:
You can't do it from python, but some clever bash tricks can do something similar. The basic reasoning is this: environment variables exist in a per-process memory space. When a new process is created with fork() it inherits its parent's environment variables. When you set an environment variable in your shell (e.g. bash) like this:
export VAR="foo"
您正在做的是告诉 bash 将其进程空间中的变量 VAR 设置为foo".当你运行一个程序时,bash 使用 fork() 然后 exec() 来运行程序,所以你从 bash 运行的任何东西都会继承 bash 环境变量.
What you're doing is telling bash to set the variable VAR in its process space to "foo". When you run a program, bash uses fork() and then exec() to run the program, so anything you run from bash inherits the bash environment variables.
现在,假设您要创建一个 bash 命令,该命令使用当前目录中名为.data"的文件中的内容设置一些环境变量 DATA.首先,你需要有一个命令来从文件中取出数据:
Now, suppose you want to create a bash command that sets some environment variable DATA with content from a file in your current directory called ".data". First, you need to have a command to get the data out of the file:
cat .data
打印数据.现在,我们要创建一个 bash 命令来在环境变量中设置该数据:
That prints the data. Now, we want to create a bash command to set that data in an environment variable:
export DATA=`cat .data`
该命令获取 .data 的内容并将其放入环境变量 DATA 中.现在,如果你把它放在一个别名命令中,你就有一个 bash 命令来设置你的环境变量:
That command takes the contents of .data and puts it in the environment variable DATA. Now, if you put that inside an alias command, you have a bash command that sets your environment variable:
alias set-data="export DATA=`cat .data`"
您可以将该别名命令放在主目录中的 .bashrc 或 .bash_profile 文件中,以便在您启动的任何新 bash shell 中都可以使用该命令.
You can put that alias command inside the .bashrc or .bash_profile files in your home directory to have that command available in any new bash shell you start.
相关文章