简体   繁体   中英

How to remove unnecessary characters from stdout in python?

I have this script:

lec_name = request.POST['selected_name']
out = run([sys.executable,'//Projects//altg//algorithm.py',lec_name], shell=False, stdout=PIPE)
print(out.stdout)

This script works fine. But I'm not getting the output properly.

OUTPUT:

b"Hello World\r\n"

EXPECTED OUTPUT:

Hello World

How can I solve this? I found lot of answers about this, but none helped. I'm using Python 3.7.4, Django 3.0.1

You can use the function strip to get copy of the array with leading and trailing spaces removed. If you are sure only trailing spaces have to be removed use rstrip

Note b'Hello World' is an array of byte, not a string, if you want to convert it to a string you can use decode("utf-8")

pi@raspberrypi:/tmp $ python3
Python 3.7.3 (default, Dec 20 2019, 18:57:59) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> b"Hello World\r\n".strip()
b'Hello World'
>>> b"Hello World\r\n".strip().decode("utf-8") 
'Hello World'
>>> 

You can use the option universal_newlines=True . Use below udpated code. If you use this you will get the expected result as Hello World.

out = run([sys.executable,'//Projects//altg//algorithm.py',lec_name], shell=False, stdout=PIPE, universal_newlines=True)

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