python version: 2.7.12 Environment: MacOS + virtualenv
I am using following code to display environment variable passed to the subprocess
from subprocess import Popen, PIPE
import os
def run_baelish(svc, cfg, dest_dir="/config", cmd=["baelish-client"]):
"""
Executes baelish command at given directory
"""
chenv = os.environ.copy()
chenv["TEST_VAR"] = "test"
print(chenv["TEST_VAR"])
try:
print(cmd)
p = Popen(cmd, stdout=PIPE, stderr=PIPE, env=chenv)
(out, err) = p.communicate()
if out is not None:
print(out)
if err is not None:
print(err)
return p.returncode
except OSError as oe:
print("baelish-client executable not found")
print(oe)
return oe.errno
except ValueError as ve:
print("Invalid arguments passed to baelish-client")
print(ve)
return 3
# end of run baelish function
I am calling this function from test code as follows:
import unittest
import os
from helper.operations import run_baelish
class TestBaelishRun(unittest.TestCase):
def setUp(self):
pass
def testSuccess(self):
run_baelish("monolith", "master", "", cmd=["echo", "$TEST_VAR"])
# End of class TestBaelish Run
after running tests I am getting following results
.test
['echo', '$TEST_VAR']
$TEST_VAR
Last line is the stdout returned by the subprocess.communicate()
call. Instead of returning the actual value of env variable its returning the echo statement as is.
EDIT: I have already tried setting shell=True
option. Even that didn't give me variable substitution.
I tried to print the entire env
inside the subprocess and it shows the variable TEST_VAR set. So I am guessing this is a problem of bash variable extrapolation inside subprocess, since its not running under any shell.
I am curious if it will affect any cmd which depends on env variables. I will run some more test.
Update:
I am closing this ticket as duplicate.
The issue was how I was passing the commands to Popen
When I changed my calls from
Popen(["/bin/echo", "$TEST_VAR"], stdout=PIPE, stderr=PIPE, env=curenv, shell=True)
to
Popen(["/bin/echo$TEST_VAR"], stdout=PIPE, stderr=PIPE, env=curenv, shell=True)
I was able to get variable substitution.