如何克服子进程调用的类型错误 python3

How to overcome Type error with subprocess call python3

下面的脚本 运行 对 python2.7 很好,而对 python3 它给出错误,这基本上只是检查磁盘文件系统 space检查。

不记得如何更正,任何帮助将不胜感激。

脚本:

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()

错误:

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'

问题是您正在尝试使用常规字符串从子进程(字节对象)中拆分 stdout.PIPE

您可以在拆分之前将输出转换为常规字符串(可能是您想要的):

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

或者您可以使用字节对象拆分它:

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

注意:您需要对 varfstmPfs 执行相同的操作。