call linux command within python
Question: > **Possible Duplicate:**  
>  [Equivalent of Backticks in
> Python](http://stackoverflow.com/questions/1410976/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.


Answer: You want [`os.stat`](http://docs.python.org/2/library/os.html#os.stat)
(specifically the `st_nlink` attribute).

_Edit:_ To paraphrase [jwz](http://www.jwz.org/): Some people, when confronted
with a problem, think "I know, I'll parse the output of `ls -l`." Now they
have two problems.

