-2

I'm trying to write a function that checks if a web server is up. I run a wget command then check the result for 200 OK in the string. I'm using the in operator but it keeps failing and I'm not sure what I'm doing wrong.

I have posted my code below.

Thanks for reading.

import subprocess

web_address = "reddit.com"
wget = subprocess.Popen(["wget", "--spider", web_address], stdout=subprocess.PIPE)
output, err = wget.communicate()
response = output.decode('utf-8')
if '200 OK' in response:
    print("its up")
else:
    print("its down")

Edit: subprocess.getoutput() solved my problem.

user252836
  • 49
  • 9

1 Answers1

0

wget logs all messages to stderr, you can capture the stderr output using stderr=subprocess.PIPE and then check err, or you can redirect stderr to stdout with stderr=subprocess.STDOUT and continue using output, e.g.:

In []:
wget = subprocess.Popen(["wget", "--spider", web_address], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output, err = wget.communicate()
'200 OK' in output.decode('utf-8')

Out[]:
True

Or using check_output() call:

In []:
output = subprocess.check_output(["wget", "--spider", web_address], stderr=subprocess.STDOUT, encoding='utf-8')
'200 OK' in output

Out[]:
True

Or using subprocess.run() (@Boris):

In []:
output = subprocess.run(["wget", "--spider", web_address], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True).stdout
'200 OK' in output

Out[]:
True
AChampion
  • 29,683
  • 4
  • 59
  • 75