Saltar al contenido

~ / código / inherit-shell-environment-in-python-for-bash-subshell

Inherit shell environment in python for bash subshell

código · 1 min · python

While executing a bash subshell inside a Python script I had to inherit the environment variables, that can be done in this way:

Bashrc

sh
$ cat ~/.bashrc |grep LOLO
export LOLO="/foo/bar"

*Here you need to restart your shell in order to execute .bashrc and export the variable.

Bash

código
#!/usr/bin/bash
echo $LOLO

Python

código
#!/usr/bin/python

import subprocess, os
my_env = os.environ.copy()
my_env["PATH"] = "/usr/sbin:/sbin:" + my_env["PATH"]
subprocess.Popen('/home/m.ortiz.montealegre/lolo/script.sh', env=my_env)

Output:

código
$ python script.py
/foo/bar

The thing is, if you add new values (aliases / variables) to your bashrc you’ll need to restart your terminal in order to bashrc to get executed and make those changes availables in the environment.

From a subshell process you can’t set environment variables to the parent shell.

Dejá un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *