![](/img/trans.png)
[英]How can I get python to read each line in a txt file and make seperate lists?
[英]How can I get a terminal output, seperate it into lines and enter it into a list of lists in python?
如何從終端獲取“service --status-all”的輸出並將其輸入到列表列表中? (每個列表包含一行)
我試過這個代碼:
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'.splitlines() 返回 ['ab c', '', 'de fg', 'kl'],而與 splitlines(True ) 返回 ['ab c\\n', '\\n', 'de fg\\r', 'kl\\r\\n']。
與 split() 給定分隔符字符串 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()
。
import os
a = os.popen('service --status-all').readlines()
output = [el.strip() for el in a]
print(output)
# ['first line', 'second line', 'third line']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.