简体   繁体   English

使用python如何只读取ping结果的第一行?

[英]using python how to read only the first line of ping results?

How to read only the first line of ping results using python? 如何使用python只读取ping结果的第一行? On reading ping results with python returns multiple lines. 在读取ping结果时,python返回多行。 So I like to know how to read and save just the 1st line of output? 所以我想知道如何阅读和保存第一行输出? The code should not only work for ping but should work for tools like "ifstat" too, which again returns multiple line results. 代码不仅应该用于ping,而且应该适用于像“ifstat”这样的工具,这又会返回多行结果。

Run the command using subprocess.check_output, and return the first of splitlines(): 使用subprocess.check_output运行命令,并返回第一个splitlines():

 import subprocess
 subprocess.check_output(['ping', '-c1', '192.168.0.1']).splitlines()[0]

Andreas 安德烈亚斯

You can use subprocess.check_output and str.splitlines . 您可以使用subprocess.check_outputstr.splitlines Here subprocess.check_output runs the command and returns the output in a string, and the you can get the first line using str.splitlines()[0] . 这里subprocess.check_output运行命令并以字符串形式返回输出,您可以使用str.splitlines()[0]获取第一行。

>>> import subprocess
>>> out = subprocess.check_output('ping google.com -c 1', shell=True)
>>> out.splitlines()[0]
'PING google.com (173.194.36.78) 56(84) bytes of data.'

Note that running a untrusted command with shell=True can be dangerous. 请注意,使用shell=True运行不受信任的命令可能很危险。 So, a better way would be: 所以,更好的方法是:

>>> import shlex
>>> command = shlex.split('ping google.com -c 1')
>>> out = subprocess.check_output(command)
>>> out.splitlines()[0]
'PING google.com (173.194.36.65) 56(84) bytes of data.'

IF you have got output in str variable ping_result, do split and access first in the array http://docs.python.org/2/library/stdtypes.html#str.split . 如果你有str变量ping_result的输出,请先在数组http://docs.python.org/2/library/stdtypes.html#str.split中进行拆分和访问。 Something like this: 像这样的东西:

first_line = ping_result.split('\\n')[0] first_line = ping_result.split('\\ n')[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM