0

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).

user3750474
  • 249
  • 5
  • 18
  • You might want to look at the answer to this question http://stackoverflow.com/questions/4760215/running-shell-command-from-python-and-capturing-the-output – Ranjith Ramachandra Jul 29 '14 at 05:32
  • This answer to another SO post might be helpful. http://stackoverflow.com/a/2339494/434551. – R Sahu Jul 29 '14 at 05:33
  • Read about the [`subprocess`](https://docs.python.org/2/library/subprocess.html) module, especially the [`Popen`](https://docs.python.org/2/library/subprocess.html#popen-constructor) class. – Some programmer dude Jul 29 '14 at 05:33

2 Answers2

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.

Ashish Gaur
  • 2,030
  • 2
  • 18
  • 32
0

You can use the subprocess module

import subprocess
output = subprocess.check_output(//unix command here)
aa333
  • 2,556
  • 16
  • 23