Read Bash variables into a Python script

后端 未结 3 1151
攒了一身酷
攒了一身酷 2021-01-31 07:37

I am running a bash script (test.sh) and it loads in environment variables (from env.sh). That works fine, but I am trying to see python can just load in the variables already i

3条回答
  •  逝去的感伤
    2021-01-31 08:24

    There's another way using subprocess that does not depend on setting the environment. With a little more code, though.

    For a shell script that looks like follows:

    #!/bin/sh
    myvar="here is my variable in the shell script"
    
    function print_myvar() {
        echo $myvar
    }
    

    You can retrieve the value of the variable or even call a function in the shell script like in the following Python code:

    import subprocess
    
    def get_var(varname):
        CMD = 'echo $(source myscript.sh; echo $%s)' % varname
        p = subprocess.Popen(CMD, stdout=subprocess.PIPE, shell=True, executable='/bin/bash')
        return p.stdout.readlines()[0].strip()
    
    def call_func(funcname):
        CMD = 'echo $(source myscript.sh; echo $(%s))' % funcname
        p = subprocess.Popen(CMD, stdout=subprocess.PIPE, shell=True, executable='/bin/bash')
        return p.stdout.readlines()[0].strip()
    
    print get_var('myvar')
    print call_func('print_myvar')
    

    Note that both shell=True shall be set in order to process the shell command in CMD to be processed as it is, and set executable='bin/bash' to use process substitution, which is not supported by the default /bin/sh.

提交回复
热议问题