Home > Blockchain >  Executing shell commands in Python
Executing shell commands in Python

Time:08-19

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?

CodePudding user response:

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

CodePudding user response:

Answer that prints the opening response as well. You may have to tweak the response if you don't want to handle it as a byte string and to handle valid but down hosts.

import subprocess

hostname= "stackoverflow.com"
try:
    response= subprocess.check_output(["ping", "-c", "1", hostname])
    print (response.split(b'\n')[0])
    print (hostname, 'is up!')
except subprocess.CalledProcessError:
    print (hostname, 'is down!')
  • Related