如何获取终端输出,将其拆分为行,并将其输入python中的列表中?
如何从终端获取服务状态的输出并将其输入列表?每个列表包含一行 我尝试过以下代码:如何获取终端输出,将其拆分为行,并将其输入python中的列表中?,python,list,Python,List,如何从终端获取服务状态的输出并将其输入列表?每个列表包含一行 我尝试过以下代码: a = os.popen('service --status-all').readlines() print a string=str(a) str=string.split('\n') 但由于某种原因,它不允许我分开这些线。 我该怎么做 谢谢您需要使用splitlines方法按行分割输出 str.splitlines[keepends]返回字符串中的行列表, 在线边界处断裂。此方法使用
a = os.popen('service --status-all').readlines()
print a
string=str(a)
str=string.split('\n')
但由于某种原因,它不允许我分开这些线。
我该怎么做
谢谢您需要使用splitlines方法按行分割输出
str.splitlines[keepends]返回字符串中的行列表,
在线边界处断裂。此方法使用通用换行符
分割线的方法。换行符不包括在列表中
结果列表,除非给出了keepends且为true
例如,“ab c\n\nde fg\rkl\r\n”。拆分行返回['ab c',
'de fg','kl'],而使用splitlinesTrue的相同调用返回['ab]
c\n','\n','de fg\r','kl\r\n']
与给定分隔符字符串sep时的拆分不同,此方法
返回空字符串的空列表和终端换行符
不会产生额外的行
此方法将运行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
你想要什么还不清楚。a已经是行的列表。试着在一行:打印行中找一行,让你自己看看。readlines函数已经将你的输入流分割成一个行列表。它在我的系统上运行得非常好。是一个列表,其中每个元素都是命令输出的一行。你能展示一下你所期望的这个程序的输出结果吗?
import os
a = os.popen('service --status-all').readlines()
output = [el.strip() for el in a]
print(output)
# ['first line', 'second line', 'third line']