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:
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:
Can you suggest a better way?
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
s = Popen(['ls', '-lf'], stdout=PIPE).stdout.read().split()
file=open("yourfile.txt","w")
for i in os.popen("ls -l"):
file.write(i)
file.close()
out = commands.getoutput("ls")
print out
out = commands.getoutput("ls")
print out
is really handy in my case, thanks for info!
lsresult = commands.getoutput('ls *.tif')
array = lsresult.split()
After that I have all *.tif files in array