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

asked Jul 29, 2014 at 5:29
3

2 Answers 2

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.

answered Jul 29, 2014 at 5:39
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the subprocess module

import subprocess
output = subprocess.check_output(//unix command here)
answered Jul 29, 2014 at 5:36

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.