Reputation: 305
I am using the following code:
import subprocess
#subprocess.call(["cat","contents.txt"])
command = "VAR=$(cat contents.txt | grep token)"
subprocess.call(command, shell = True)
subprocess.call(["echo","$VAR"])
I am trying to assign value of token present in contents.txt to a variable and i am trying to print the variable. But i am not getting anything. What corrections can be done here.
Thanks
Upvotes: 0
Views: 790
Reputation: 1937
You got to do everything in one process, since os.environ
is for the particular python process and subprocess
executes your commands in another process, you can't access it from there.
you also can't do it in two different subprocess.call
calls since each is another process and you could not access the variable from the second one, therefore you have to execute everything in the same process, all commands at the same line, separated by ";", as follows:
import subprocess
result = subprocess.run('VAR=$(cat contents.txt | grep token); echo $VAR', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print(result.stdout.decode())
in my contents.txt
file I have "token=123", and hence the result of result.stdout.decode()
was "token=123" as well :D
Upvotes: 2