Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to overcome Type error with subprocess call python3

The below script was running fine with python2.7 while with python3 its giving error, this is just basically to check the disk file-system space check.

can not recall how to correct , any help will be much appreciated.

Script:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import subprocess
import socket
threshold = 10
hst_name = (socket.gethostname())

def fs_function(usage):
   return_val = None
   try:
      return_val = subprocess.Popen(['df', '-Ph', usage], stdout=subprocess.PIPE)
   except IndexError:
      print("Mount point not found.")
   return return_val


def show_result(output, mount_name):
   if len(output) > 0:
      for x in output[1:]:
          perc = int(x.split()[-2][:-1])
          if perc >= threshold:
            print("Service Status:  Filesystem For " + mount_name + " is not normal and " + str(perc) + "% used on the host",hst_name)
          else:
            print("Service Status:  Filesystem For " + mount_name + " is normal on the host",hst_name)
def fs_main():
   rootfs = fs_function("/")
   varfs  = fs_function("/var")
   tmPfs = fs_function("/tmp")

   output = rootfs.communicate()[0].strip().split("\n")
   show_result(output, "root (/)")

   output = varfs.communicate()[0].strip().split("\n")
   show_result(output, "Var (/var)")

   output = tmPfs.communicate()[0].strip().split("\n")
   show_result(output, "tmp (/tmp)")
fs_main()

Error:

Traceback (most recent call last):
  File "./fsusaage.py", line 42, in <module>
    fs_main()
  File "./fsusaage.py", line 34, in fs_main
    output = rootfs.communicate()[0].strip().split("\n")
TypeError: a bytes-like object is required, not 'str'

>Solution :

The issue is that you are trying to split the stdout.PIPE from the subprocess—a bytes object—using a regular string.

You can either convert the output to a regular string before splitting it (probably what you want):

output = str(rootfs.communicate()[0]).strip().split('\n')

or you can split it using a bytes object:

output = rootfs.communicate()[0].strip().split(b'\n')

Note: you will need to do the same for varfs and tmPfs.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading