<p>可以使用<a href="http://docs.python.org/library/os.html#os.popen">^{<cd1>}</a>运行命令并检索其输出,然后使用<a href="http://docs.python.org/library/stdtypes.html#str.splitlines">^{<cd2>}</a>和<a href="http://docs.python.org/library/stdtypes.html#str.split">^{<cd3>}</a>拆分行和字段。运行<a href="http://pubs.opengroup.org/onlinepubs/009695399/utilities/df.html">^{<cd4>}</a>,而不是<code>df -h</code>,这样,如果列太长,就不会拆分行。</p>
<pre><code>df_output_lines = [s.split() for s in os.popen("df -Ph").read().splitlines()]
</code></pre>
<p>结果是一个行列表。要提取第一列,可以使用<code>[line[0] for line in df_output_lines]</code>(注意,列是从0开始编号的)等。您可能需要使用<code>df_output_lines[1:]</code>而不是<code>df_output_lines</code>来删除标题行。</p>
<p>如果已经将<code>df -h</code>的输出存储在某个文件中,则需要首先连接这些行。</p>
<pre><code>fixed_df_output = re.sub('\n\s+', ' ', raw_df_output.read())
df_output_lines = [s.split() for s in fixed_df_output.splitlines()]
</code></pre>
<p>注意,这假定文件系统名和装入点都不包含空格。如果是这样的话(这在某些unix变体上的一些设置中是可能的),几乎不可能解析<code>df</code>,甚至<code>df -P</code>的输出。您可以使用<a href="http://docs.python.org/library/os.html#os.statvfs">^{<cd12>}</a>来获取给定文件系统的信息(这是<a href="http://pubs.opengroup.org/onlinepubs/009695399/functions/statvfs.html">C function</a>的Python接口,该接口在内部为每个文件系统调用,<code>df</code>),但是没有枚举文件系统的可移植方法。</p>