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
hostname= "server.com" response= os.system("ping -c 1 " + hostname) if response == 0: print (hostname, 'is up!') else: print (hostname, 'is down!')
Output:
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!
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
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