0

可能的重复:
Python 中反引号的等价物

我正在寻找在 Python 中运行终端命令 (ls -l) 的最佳方式。我已经阅读了有关子流程的信息,但我并不完全理解它,如果有人可以尝试让我了解正在发生的事情,我将不胜感激。我需要使用 ls -l 命令来检索一个硬链接号码,它是 != 1,然后保存这个号码以将它与其他地方的目录号码相匹配。现在我只想知道如何获取硬链接号并使用子进程将其保存到一个变量中(或者如果有一个更好的方法)。

这是我到目前为止使用的代码:#!/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") 输出我需要的信息,但不会将其保存到我创建的文件中。我在别处读到 os.system 不会输出数据。

4

2 回答 2

6

你想要os.stat(特别是st_nlink属性)。

编辑:解释jwz:有些人在遇到问题时会想“我知道,我会解析ls -l.”的输出。现在他们有两个问题。

于 2012-12-14T23:32:24.847 回答
2

您可以将file对象传递给stdoutinsubprocess.call()并且输出将保存到该文件中:

In [26]: import subprocess

In [27]: with open("data.txt","w") as f:
    subprocess.call("ls -la",stdout=f,shell=True)
   ....:   
于 2012-12-14T23:31:50.090 回答