代码之家  ›  专栏  ›  技术社区  ›  krock1516

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

  •  0
  • krock1516  · 技术社区  · 4 年前

    下面的脚本在python2中运行良好。7虽然python3给出了错误,但这基本上只是检查磁盘文件系统空间检查。

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

    脚本:

    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'
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   baileythegreen    4 年前

    问题是,你正在试图分割 stdout.PIPE 从子流程使用常规字符串创建字节对象。

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

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

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

    注意:你也需要这样做 varfs tmPfs .