【问题标题】:How to set parent process' shell env from child process如何从子进程设置父进程的外壳环境
【发布时间】:2015-05-06 10:57:22
【问题描述】:

子进程有一个必须传递给父进程的值。我正在使用 python 的 subprocess.Popen 来执行此操作,但子进程的 TEMP_VAR 在父 shell 中不可见?

import subprocess
import sys

temp = """variable_val"""
subprocess.Popen('export TEMP_VAR=' + temp + '&& echo $TEMP_VAR', shell=True)
//prints variable_val
subprocess.Popen('echo $TEMP_VAR', shell=True)
//prints empty string

有没有办法在不使用queues(或)Popen's - stdout/stdin 关键字参数的情况下进行这种进程间通信。

【问题讨论】:

    标签: python shell subprocess inter-process-communicat


    【解决方案1】:

    环境变量从父级复制到子级,它们不会共享或沿另一个方向复制。 export 所做的只是在子进程中创建一个环境变量,这样子进程就会看到它。

    最简单的方法是在子进程中echo(我假设它是一个shell脚本)并使用管道在python中捕获它。

    Python:

    import subprocess
    
    proc = subprocess.Popen(['bash', 'gash.sh'], stdout=subprocess.PIPE)
    
    output = proc.communicate()[0]
    
    print "output:", output
    

    重击(gash.sh):

    TEMP_VAR='yellow world'
    echo -n "$TEMP_VAR"
    

    输出:

    output: yellow world
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-10
      • 2018-09-08
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      • 1970-01-01
      相关资源
      最近更新 更多