简体   繁体   中英

Python 2.7 read exported variables from bash

I have a python2.7 script which is calling a bash script, inside the bash script i'm exporting 2 variable i've tried with declare -x and with export , then i'm trying to read this variables in the python script using os.getenv and i also tried using os.environ but i'm getting a None type each time. Here is a snippet from my scripts:

Python:

def set_perforce_workspace():
        global workspace_path
        global workspace_root_path
        script_path = "somePath"
        depot_name = "TestingTools"
        dir_to_download = "vtf"
        bash_command = "./createWorkspace.sh " + "-d " + depot_name + " -w " \
                       + PerforceUtils.WORKSPACE_NAME + " -a " + dir_to_download
        print bash_command
        print os.getcwd()
        try:
            os.chdir(script_path)
        except OSError as e:
            print "Error: {0}".format(e)
        print os.getcwd()
        return_code = call([bash_command], shell=True)
        test = os.getenv("workspace_path")
        print "this is test {0}".format(test)
        workspace_path = os.getenv("workspace_path")
        workspace_root_path = os.getenv("workspace_root_path")
        print "This is the return code {0}".format(return_code)
        print "this is the workspace path: {0}".format(workspace_path)
        print "this is the workspace root path: {0}".format(workspace_root_path)
        return return_code

Bash:

declare -x workspace_root_path="$workspaceProjPath"
export workspace_path="$workspaceProjPathLocal"

From the documentation for os.environ :

This mapping is captured the first time the os module is imported, typically during Python startup as part of processing site.py. Changes to the environment made after this time are not reflected in os.environ, except for changes made by modifying os.environ directly.

So basically when your bash script changes the environment and then goes back to your python script the environment variables aren't refreshed. Pretty annoying. As the docs say the best solution is to add your variables to the environ list directly, like:

os.environ['PATH'] = '/bin/'

How you accomplish this is up to you, piping is a pretty decent way to do it. Albeit annoying. Unfortunately there is no way to "refresh" the environment list. In a lot of situations it might be best just to drop your bash script and somehow adapt it to the python script.

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