Execute Linux commands in Python

For last few days, I am doing an interesting project, for which I require to execute some Linux commands from Python. So I searched a bit for it and found an way to do it. For example if I want to run the command 'ls -lt', I can use the following code:

import os
os.system('ls -lt')


But problem is I want to store the result in a list. Then I thought of writing the output to a file and read the file into a list. My code was:

import os
os.system('ls -lt > output.txt')



Can you suggest a better way?

Comments

Ivan Illarionov said…
from subprocess import Popen, PIPE
s = Popen(['ls', '-lf'], stdout=PIPE).stdout.read().split()
王同 said…
Yeah, you can do with os.popen too.

file=open("yourfile.txt","w")
for i in os.popen("ls -l"):
file.write(i)
file.close()
Julian_Belfort said…
Hey thanks for the info! just what i needed
Felipe said…
import commands
out = commands.getoutput("ls")
print out
Venkat said…
import commands
out = commands.getoutput("ls")
print out

is really handy in my case, thanks for info!
Thanks to Subeen and those who wrote very useful comments.
Anatoliy said…
This one commands help me.
lsresult = commands.getoutput('ls *.tif')
array = lsresult.split()

After that I have all *.tif files in array
Unknown said…
This is just what I NEED! Thank you so much, dude!!

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code