简体   繁体   中英

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. 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:

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

Try with

os.environ['LINE'] = var

instead of using putenv . Using putenv "bypasses" os.environ , that is, it doesn't update os.environ .

In fact, from the documentation for os.putenv :

Assignments to items in os.environ are automatically translated into corresponding calls to putenv(); however, calls to putenv() don't update os.environ, so it is actually preferable to assign to items of os.environ. This also applies to getenv() and getenvb(), which respectively use os.environ and os.environb in their implementations."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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