我怎样才能得到一个终端输出,把它分成几行,然后在python中输入一个列表列表?

2024-04-24 00:47:18 发布

您现在位置:Python中文网/ 问答频道 /正文

如何从终端获取“service--status all”的输出并将其输入到列表中?(每个列表包含一行)

我尝试过以下代码:

a  = os.popen('service --status-all').readlines()
    print a
    string=str(a)
    str=string.split('\n')

但由于某种原因,它不允许我把线分开。 我该怎么做?你知道吗

谢谢


Tags: 代码终端列表stringosstatusserviceall
2条回答

您需要使用splitlines方法按行分割输出

str.splitlines([keepends]) Return a list of the lines in the string, breaking at line boundaries. This method uses the universal newlines approach to splitting lines. Line breaks are not included in the resulting list unless keepends is given and true.

For example, 'ab c\n\nde fg\rkl\r\n'.splitlines() returns ['ab c', '', 'de fg', 'kl'], while the same call with splitlines(True) returns ['ab c\n', '\n', 'de fg\r', 'kl\r\n'].

Unlike split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line.

此方法将运行shell命令并返回行列表:

def run_shell_command_multiline(cmd):
        p = subprocess.Popen([cmd], stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        stdout, stderr = p.communicate()
        if p.returncode != 0:
            raise RuntimeError("%r failed, status code %s stdout %r stderr %r" % (
                cmd, p.returncode, stdout, stderr))
        return stdout.splitlines()  # This is the stdout from the shell command

使用.readlines()已经将输出分成几行。你知道吗

如果您想摆脱额外的\n,还可以使用.strip()。你知道吗

import os

a = os.popen('service  status-all').readlines()
output = [el.strip() for el in a]

print(output)

# ['first line', 'second line', 'third line']

相关问题 更多 >