I'm trying to run a shell script in python and save the output to a variable.
This is my python script:
import os
os.system("sh ./temp.sh > outfile.txt")
file = open("outfile.txt", "r")
var = file.readLine()
#I do more stuff using var
Right now this works. However is there a more efficient way to do this? It seems a little inefficient to output to a file and then read from the file again. My goal is to set var directly from the output of the os command. For example var = os.system(unix command). (I know this doesn't work).
2 Answers 2
You can use the subprocess module to store the output in a variable, thus making your script something like this :
import subprocess
var = subprocess.check_output(['sh', 'temp.sh']) //
The subprocess module basically allows you to execute shell commands which passed to it as an array of arguments so like to execute ls -l you need to pass it as ['ls', '-l'], similarly you can pass call to your script as above. You can read about subprocess here.
Comments
You can use the subprocess module
import subprocess
output = subprocess.check_output(//unix command here)
subprocessmodule, especially thePopenclass.