Home > Blockchain >  How do I get rid of b' if I want to parse a bash output using python?
How do I get rid of b' if I want to parse a bash output using python?

Time:10-26

At my python application I'm doing the following to get some values from a larger JSON

ffgrading_json = exec_command(f'{options["path_ffprobe"]} -loglevel quiet -print_format json -read_intervals "% #2" -select_streams v:0 -show_entries side_data "{path}" | egrep -m 1 -A 10 "Mastering display metadata" | grep -v "Mastering display metadata"|tr -d "[:space:]"| tr -d "\n"')

on the bash console, the raw command returns the following:

"red_x":"34000/50000","red_y":"16000/50000","green_x":"13250/50000","green_y":"34500/50000","blue_x":"7500/50000","blue_y":"3000/50000","white_point_x":"15635/50000","white_point_y":"16450/50000","min_luminance":"50/10000","max_luminance":"40000000/10000"

But if I write the output to a file using python like so:

with open('/tmp/grading.json', 'w') as f:
                f.write(str(ffgrading_json))

The following will get written: b'"red_x":"34000/50000","red_y":"16000/50000","green_x":"13250/50000","green_y":"34500/50000","blue_x":"7500/50000","blue_y":"3000/50000","white_point_x":"15635/50000","white_point_y":"16450/50000","min_luminance":"50/10000","max_luminance":"40000000/10000"'

Not sure how important it is but this is my exec_command function:

def exec_command(string):
    """
    Shell command interface
    Returns returnCode, stdout, stderr
    """
    log('DEBUG', f'[Command] {string}')
    output = run(string, shell=True, check=True, capture_output=True)
    return output.returncode, output.stdout, output.stderr

The question now is, how can I get rid of b' and where does it come from ???

CodePudding user response:

you need to use .decode() on the output.stdout the output is in bytes so this will convert it to a string

when you print bytes python tries to convert what it can into ascii characters but it will display b'' around the printed data to indicate that the variable you printed contains bytes and it is not a string

  • Related