Python从元组转换为字符串

时间:2013-01-27 17:27:45

标签: python string tuples

我知道你们很多人这很容易做,但对我来说没有。所以我正在尝试从shell输出数据,但是当我必须将其转换为字符串时,我被困住了。我试过for,但没有用。所以基本上,我正在尝试的是:对于我的shell中的每个新行,输出新行。我举一个例子 - free -m命令。它的输出是

  total       used       free     shared    buffers     cached
  Mem:           144        512        111          0          0        121
  -/+ buffers/cache:         23        232
  Swap:            0          0          0

所以,到目前为止我写的是:

import commands
foo...
sout = commands.getstatusoutput(inp)
    return ' '.join(str(line) for line in sout)
foo...

但是输出只有一行(第一行 - 总计,使用,免费,共享等)

我希望每个新行都有新行,就像shell中的输出一样。如果我在没有.join的情况下离开它,它会输出类似

的内容
(0, '             total       used       free     shared    buffers     cached\nMem:           512        144        368          0          0        121\n-/+ buffers/cache:         21        234\nSwap:            0          0          0')

由于我希望它是一个字符串,我甚至尝试'\n'.join,但它只输出0(wtf)。有什么想法吗?

4 个答案:

答案 0 :(得分:1)

你也可以使用更方便的os.popen。

print os.popen('free -m').read()

您可能希望阅读此主题,以便从python Calling an external command in Python

中获取可用于运行shell命令的选项的概述

答案 1 :(得分:0)

整个字符串都在元组中,有换行符和所有内容,所以我想你需要做的就是:

print sout[1]

假设sout是您在问题中显示的元组:

(0, '             total       used       free     shared    buffers     cached\nMem:           512        144        368          0          0        121\n-/+ buffers/cache:         21        234\nSwap:            0          0          0')

答案 2 :(得分:0)

只需检查换行符,然后在输出中插入换行符。实际上你在整体上得到了输入。希望它有所帮助

答案 3 :(得分:0)

还有另一种方法可以获得相同的结果:

    from subprocess import Popen, PIPE
    // Create a subprocess and then interact with the process by reading data from 
    // stdout, untill the end-of-file is reached. Since communicate return tuple 
    // in the form of stdout, stderr), Capture only the output.

    (result, errcode) = Popen('free -m', stdout = PIPE, shell = True).communicate()
    print result
相关问题