Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I run a bash script in Python and keep any env variables it exports?

The title pretty much says it all..

Suppose I have a bash script:

#!/bin/bash

# do some magic here, perhaps fetch something with wget, and then:
if [ "$VAR1" = "foo" ]; then
    export CASEVARA=1
fi
export CASEVARB=2

# and potentially many other vars...

How can I run this script from python and check what env variables were set. Ideally, I'd like to "reverse-inherit" them into the main environment that is running Python.

So that I can access them with

import os

# run the bash script somehow

print os.environ['CASEVARA']
like image 207
frnhr Avatar asked Apr 09 '14 16:04

frnhr


People also ask

Does shell script inherit environment variable?

Environment variables are inherited by child shells but shell variables are not. Shell variable can be made an environment variable by using export command.

Can we use bash script in Python?

Bash is an implementation of the shell concept and is often used during Python software development as part of a programmer's development environment.

Does export set environment variable?

The export command is used to set Environment variables. Environment Variables created in this way are available only in the current session. If you open a new shell or if you log out all variables will be lost.

What is the benefit of using environment variables in shell scripts?

Environmental Variables contain all variables defined system-wide and available to every child shells or processes. They help pass information into the processes you start through the shell commands.


2 Answers

Certainly! It just requires some hacks:

variables = subprocess.Popen(
    ["bash", "-c", "trap 'env' exit; source \"$1\" > /dev/null 2>&1",
       "_", "yourscript"],
    shell=False, stdout=subprocess.PIPE).communicate()[0]

This will run your unmodified script and give you all exported variables in the form foo=bar on different lines.

On supported OS (like GNU) you can trap 'env -0' exit to get \0 separated variables, to support multiline values.

like image 172
that other guy Avatar answered Oct 18 '22 21:10

that other guy


Use the subprocess module:

  • Echo the variables out in your shell script
  • Run the bash script from python using subprocess.Popen with stdout=subprocess.PIPE set
  • Pick them up using subprocess.communicate()
  • Save them to python variables
like image 2
FarmerGedden Avatar answered Oct 18 '22 22:10

FarmerGedden