I’m working in Linux/Python 3 and am creating some small scripts which consist of executing some commands inside of Python.
Example: Pinging a server
JavaScript
x
7
1
hostname= "server.com"
2
response= os.system("ping -c 1 " + hostname)
3
if response == 0:
4
print (hostname, 'is up!')
5
else:
6
print (hostname, 'is down!')
7
Output:
JavaScript
1
8
1
PING server.com (10.10.200.55) 56(84) bytes of data.
2
64 bytes from server.com (10.10.200.55): icmp_seq=1 ttl=61 time=12.4 ms
3
4
--- server.com ping statistics ---
5
1 packets transmitted, 1 received, 0% packet loss, time 0ms
6
rtt min/avg/max/mdev = 15.446/15.446/15.446/0.000 ms
7
server.com is up!
8
This is working OK but I don´t need to print everything. How can I get only the first line of the output?
Advertisement
Answer
You can use a subprocess in python3 to discard the output to devnull. Something like this
JavaScript
1
12
12
1
import subprocess
2
3
hostname= "server.com"
4
response= subprocess.call(["ping", "-c", "1", hostname],
5
stdout=subprocess.DEVNULL,
6
stderr=subprocess.STDOUT)
7
8
if response == 0:
9
print (hostname, 'is up!')
10
else:
11
print (hostname, 'is down!')
12
https://docs.python.org/3/library/subprocess.html#subprocess.DEVNULL