我在Linux/Python3中工作,正在创建一些小脚本,这些脚本由在Python中执行一些命令组成.

示例: 对服务器执行ping操作

hostname= "server.com"
response= os.system("ping -c 1 " + hostname)
if response == 0:
    print (hostname, 'is up!')
else:
    print (hostname, 'is down!')

输出:

PING server.com (10.10.200.55) 56(84) bytes of data.
64 bytes from server.com (10.10.200.55): icmp_seq=1 ttl=61 time=12.4 ms

--- server.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 15.446/15.446/15.446/0.000 ms
server.com is up!

这个可以正常工作,但我不需要全部打印. 我如何才能只得到输出的第一行?

推荐答案

您可以使用python3中的子进程将输出丢弃到devNULL.像这样的东西

import subprocess

hostname= "server.com"
response= subprocess.call(["ping", "-c", "1", hostname], 
stdout=subprocess.DEVNULL,
stderr=subprocess.STDOUT)

if response == 0:
  print (hostname, 'is up!')
else:
  print (hostname, 'is down!')

https://docs.python.org/3/library/subprocess.html#subprocess.DEVNULL

Python相关问答推荐

使用pandas MultiIndex进行不连续 Select

调试回归无法解决我的问题

如何对行使用分段/部分.diff()或.pct_change()?

pyautogui.locateOnScreen在Linux上的工作方式有所不同

从管道将Python应用程序部署到Azure Web应用程序,不包括需求包

如何处理嵌套的SON?

如何计算两极打印机中 * 所有列 * 的出现次数?

ModuleNotFound错误:没有名为Crypto Windows 11、Python 3.11.6的模块

如何在类和classy-fastapi -fastapi- followup中使用FastAPI创建路由

Pandas—在数据透视表中占总数的百分比

在Python中,从给定范围内的数组中提取索引组列表的更有效方法

多指标不同顺序串联大Pandas 模型

未知依赖项pin—1阻止conda安装""

调用decorator返回原始函数的输出

可以bcrypts AES—256 GCM加密损坏ZIP文件吗?

Geopandas未返回正确的缓冲区(单位:米)

python panda ExcelWriter切换动态公式到数组公式

如何在两列上groupBy,并使用pyspark计算每个分组列的平均总价值

如何使用OpenGL使球体遵循Python中的八样路径?

提高算法效率的策略?