简体   繁体   English

Python中如何制作环境变量

[英]How to make environment variable in Python

I need a help in making variables as ENV in python, so that I can see that variable by using 'export' command in Linux. So I tested a below short script and I can see variable using export command.我需要帮助在 python 中将变量设为 ENV,以便我可以在 Linux 中使用“导出”命令查看该变量。所以我测试了下面的简短脚本,我可以使用导出命令查看变量。 But the problem is that, below two command didn't work.但问题是,下面的两个命令不起作用。

var1 = os.environ['LINE']
print(var1)

Can you guide me how can I get this solved?你能指导我如何解决这个问题吗?

import os
import json
import sys

Name = "a1"
def func():
        var = 'My name is ' + '' + Name
        os.putenv('LINE', var)
        os.system('bash')

func()

var1 = os.environ['LINE']
print(var1)

Output: Output:

export | grep LINE
declare -x LINE="My name is a1"

Try with试试

os.environ['LINE'] = var

instead of using putenv .而不是使用putenv Using putenv "bypasses" os.environ , that is, it doesn't update os.environ .使用putenv “绕过” os.environ ,也就是说,它不会更新os.environ

In fact, from the documentation for os.putenv :事实上,从os.putenv的文档

Assignments to items in os.environ are automatically translated into corresponding calls to putenv();对 os.environ 中项目的分配会自动转换为对 putenv() 的相应调用; however, calls to putenv() don't update os.environ, so it is actually preferable to assign to items of os.environ.然而,对 putenv() 的调用不会更新 os.environ,因此实际上最好分配给 os.environ 的项目。 This also applies to getenv() and getenvb(), which respectively use os.environ and os.environb in their implementations."这也适用于 getenv() 和 getenvb(),它们分别在其实现中使用 os.environ 和 os.environb。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM