0

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

4
  • Have you checked your file exists and it is in PATH or local folder? Commented Jul 1, 2021 at 7:36
  • You can more easily access environment variables with os.environ Commented Jul 1, 2021 at 7:39
  • Have you looked into subprocess.check_output? docs.python.org/3/library/… Commented Jul 1, 2021 at 7:42
  • @SlLoWre yes i am sure file is in same path. Because above command is working Commented Jul 1, 2021 at 7:43

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.