繁体   English   中英

Python 2.7从bash读取导出的变量

[英]Python 2.7 read exported variables from bash

我有一个python2.7脚本正在调用bash脚本,在bash脚本中我正在导出2个我已经尝试过的declare -x带有declare -xexport变量,然后我试图使用以下命令在python脚本中读取此变量os.getenv和我也尝试使用os.environ但每次都得到None类型。 这是我的脚本的片段:

蟒蛇:

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

重击:

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

os.environ的文档中:

首次导入os模块时(通常是在Python启动期间作为处理site.py的一部分)捕获了此映射。 此时间之后对环境所做的更改不会反映在os.environ中,除非直接通过修改os.environ进行更改。

因此,基本上,当您的bash脚本更改环境然后返回到python脚本时,不会刷新环境变量。 真烦人。 正如文档所说,最好的解决方案是将变量直接添加到环境列表中,例如:

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

如何完成此操作取决于您,管道是一种相当不错的方法。 尽管烦人。 不幸的是,没有办法“刷新”环境列表。 在许多情况下,最好只是删除bash脚本并以某种方式使其适应python脚本。

暂无
暂无

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

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