2

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?

3
  • Hey are you on linux or windows? Commented Aug 17, 2022 at 18:02
  • Hey there. I am in Linux Commented Aug 18, 2022 at 8:22
  • Which version of Python 3 are you using? Commented Aug 18, 2022 at 13:40

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

5 Comments

check_output has no stdout flag.
I get this error: raise ValueError('stdout argument not allowed, it will be overridden.') ValueError: stdout argument not allowed, it will be overridden.
Apologies. changed it to call. Should work now.
Looks nice now. Thanks. How can I get the first line of the output for example?
youd have to set response= subprocess.check_output(["ping", "-c", "1", hostname]) then parse that response manually. You'd also have to use a try/except because if host is invalid it will throw an exception
0

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!')

2 Comments

Output: b'PING stackoverflow.com (151.101.193.69) 56(84) bytes of data.' Anyway to get rid of the b' and last ', from the output?
you'd have to convert the byte string to a regular string. you can try wrapping it in str() but I'm not 100% on that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.