What I am trying to achieve is - to run and return output of some automation scripts, but I am failing to understand why I can't use ENV vars in my scripts?
A simple example I am struggling to implement
import os
import subprocess as sp
cmd = [ 'echo', '$_TEST' ]
myenv = {**{'_TEST':"is it working?"}, **os.environ }
pipe = sp.Popen( cmd, stdout=sp.PIPE, stderr=sp.PIPE, env=myenv );
print( pipe.communicate() )
What I am doing wrong?
Update: after getting correct answer.
import os
import subprocess as sp
cmd = [ '/bin/echo', '$_TEST' ]
myenv = {**{'_TEST':"is it working?"}, **os.environ }
pipe = sp.Popen( " ".join(cmd), stdout=sp.PIPE, shell=True, stderr=sp.PIPE, env=myenv );
print( pipe.communicate() )
Need to provide a shell argument shell=True
(or provide a path to other shell), shell we need to evaluate our variables.
list
of commands should be replaced by string
(eg '/bin/echo $_TEST')
The substitution of environment variables is performed by shell, so your solution just prints original text. The proper way to solve this task:
import os
import subprocess as sp
cmd = 'echo $_TEST'
myenv = {**{'_TEST':"is it working?"}, **os.environ }
pipe = sp.Popen( cmd, shell=True, stdout=sp.PIPE, stderr=sp.PIPE, env=myenv );
print( pipe.communicate() )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.