简体   繁体   中英

How to strip and removed special characters from the out put of python sub process

I am using Python sub process to execute command as shown below:

process = subprocess.Popen(['debug', 'file.tgz'], 
                           stdout=subprocess.PIPE,stderr=subprocess.PIPE)


while True:
    output = process.stdout.readline()
    print(str(output.strip()).encode())
    return_code = process.poll()

    if return_code is not None:
         break 

What i am getting out put is shown below:

b"b'Registers:'"

And this is what i am expecting.

Registers:

I am using encode but still seeing same out put. If i run the same process on command line i am getting the same desired out put.

How can i remove these special characters?

  • Skip the str(); that'll get rid of the inner b'...'
  • You want to.decode rather than.encode, because you want to turn a byte-stream (which came from the subprocess) into a string (for printing). You'll need to know which encoding it's using, and (if applicable) what to do with malformed data.
  • (optional) Strip the whitespace after decoding, not before, to also strip non-ASCII whitespace characters (if any).
    print(output.decode('utf8', errors='strict').strip())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM