Question

Possible Duplicate:
Equivalent of Backticks in Python

I am looking for the best way to run a terminal command (ls -l) within Python. I have read about subprocess but I do not understand it fully, if someone could try and make me understand what is happening I would be grateful. I need to use the ls -l command to retrieve a hard link number which is != 1 and then save this number to match it against a directory number elsewhere. For now I would just like to know how to grab the hard link number and save it to a variable using subprocess (or a better method if there is one).

Here is the code I have used so far: #!/usr/bin/python

#tool that resolves time machine directories 

import os

#create output file 
os.chdir("/home/sean/Desktop")
hard_link_number = open('hardLinkNumber.log', 'w')

#move into mounted backup (figure out how to remove xe2 etc)
os.chdir("/mnt/Backups.backupdb/stuart dent\xe2\x80\x99s MacBook Pro/2010-08-10-160859/MAc")

#find hard link data 
print>>hard_link_number, os.system("ls -la")
hard_link_number.close()

os.system("ls -la") outputs the information I require but it will not save it to the file I have created. I read elsewhere that os.system will not output data.

Was it helpful?

Solution

You want os.stat (specifically the st_nlink attribute).

Edit: To paraphrase jwz: Some people, when confronted with a problem, think "I know, I'll parse the output of ls -l." Now they have two problems.

OTHER TIPS

You can pass the file object to stdout in subprocess.call() and the output will be saved to that file:

In [26]: import subprocess

In [27]: with open("data.txt","w") as f:
    subprocess.call("ls -la",stdout=f,shell=True)
   ....:   
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top