为什么python中的环境变量不能持续存在? [英] Why can't environmental variables set in python persist?

查看:202
本文介绍了为什么python中的环境变量不能持续存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望通过在任何目录中运行脚本来编写一个适当的环境变量来创建一些适当的环境变量,我将会看到,我无法编写一个脚本来使这些env vars持续在mac os终端。所以两件事:



这是真的吗?





似乎这将是一件有用的事情;为什么不可能一般?

解决方案

你不能从python做,但一些聪明的bash技巧可以做相似的东西。基本推理是这样的:环境变量存在于每个进程的内存空间中。当使用fork()创建新进程时,它将继承其父环境变量。当你在shell中设置一个环境变量(例如bash):

  export VAR =foo

您正在做的是告诉bash将进程空间中的变量VAR设置为foo。当您运行程序时,bash使用fork()然后exec()来运行程序,所以从bash运行的任何内容都会继承bash环境变量。



现在,假设您要创建一个bash命令,它将当前目录中名为.data的文件中的内容设置为一些环境变量DATA。首先,您需要有一个命令来从文件中获取数据:

  cat .data 

打印数据。现在,我们要创建一个bash命令来设置环境变量中的数据:

  export DATA =`cat .data` 

该命令使用.data的内容并将其放在环境变量DATA中。现在,如果你把它放在别名命令中,你有一个bash命令来设置你的环境变量:

 别名set-data =export DATA =`cat .data`

您可以将该别名命令放在.bashrc中或.bash_profile文件在您的主目录,以使该命令可用于任何新的bash shell启动。


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:

Is this true?

and

It seems like it would be a useful things to do; why isn't it possible in general?

解决方案

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"

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.

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

That prints the data. Now, we want to create a bash command to set that data in an environment variable:

export DATA=`cat .data`

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`"

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.

这篇关于为什么python中的环境变量不能持续存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆