How to remove b symbol in python3

前端 未结 1 1359
长发绾君心
长发绾君心 2021-01-05 16:08

How to remove b symbol from python3 script?

import subprocess

get_data=subprocess.check_output([\"df -k | awk \'{print $6}\'\"],shell=True)
dat         


        
相关标签:
1条回答
  • 2021-01-05 16:40

    The b symbol indicates that the output of check_process is a bytes rather than a str. The best way to remove it is to convert the output to string before you do any further work on it:

    byte_data=subprocess.check_output(["df -k | awk '{print $6}'"],shell=True)
    str_data = byte_data.decode('utf-8')
    data_arr=str_data.split()
    ...
    

    The decode method will take care of any unicode you may have in the string. If your default encoding (or the one used by awk I suppose) is not UTF-8, substitute the correct one in the example above.

    Possibly an even better way to get around this issue is to tell check_output to open stdout as a text stream. The easiest way is to add a universal_newlines=True argument, which will use the default encoding for your current locale:

    str_data = subprocess.check_output(["df -k | awk '{print $6}'"], shell=True, universal_newlines=True)
    

    Alternatively, you can specify an explicit encoding:

    str_data = subprocess.check_output(["df -k | awk '{print $6}'"], shell=True, encoding='utf-8')
    

    In both of these cases, you do not need to decode because the output will already be str rather than bytes.

    0 讨论(0)
提交回复
热议问题