Reputation: 63
I am trying to open a gif file, and send its bytes properly to a webbrowser but it throws the exception 'cannot convert 'bytes' object to str implicitly' and frankly I am baffled, because I already converted it to a string.
files=open("WebContent/"+fileName,"rb")
#size=os.path.getsize("WebContent/"+fileName)
text=str(files.read())
text=text.encode('UTF-8')
defaultResponseCode="HTTP/1.1 200 OK\r\nContent-Type: image/gif\r\nContent-Transfer-Encoding: binary\r\nContent-Length: 29696\r\n\r\n"+text
Thanks in advance!
Upvotes: 5
Views: 16976
Reputation: 1
In python 3+ I was getting similar problem, and I removed text.encode("utf-8")
and used text.strip()
.
text = text.strip()
Upvotes: 0
Reputation: 674
For those primarily interested in Popen rather than psql, here's a debugged working python3 script, based the original Popen question, and incorporating provided suggestions.
#!/usr/bin/env python3
# print a list of postgresql databases via psql
import subprocess
username = "postgres"
dbname = "postgres"
p = subprocess.Popen(
args = ['psql', '-qAt', '-U', username, '-d', dbname],
# args = ['psql', '-qAt', '-d', dbname], # with adequate user permissions
stdin = subprocess.PIPE,
stdout = subprocess.PIPE
)
sql = b"SELECT datname FROM pg_database;"
dbs = p.communicate(b"SELECT datname FROM pg_database;")[0].split(b'\n')
for db in dbs:
print("%s" % db.decode("utf-8"))
p.wait()
Upvotes: 0
Reputation: 22561
Here you are trying to convert bytes (file opened with 'rb'
mode) to string:
text = str(files.read())
change above line to this:
text = files.read().decode(encoding='change_to_source_file_encoding')
then you can convert unicode string to utf-8 byte string with:
text = text.encode('UTF-8')
And if source encoding is utf-8 you can just pass byte string from files.read()
to your result string without senseless decode/encode steps (from utf-8 bytes to string and again to utf-8 bytes)...
update: try with requests
url = 'url'
files = {'file': open("WebContent/"+fileName, 'rb')}
response = requests.post(url, files=files)
update 2:
According to content-type in response header (... Content-Type: image/gif ...
) you have data with needed format just after files.read()
whithout any encoding/decoding!
Upvotes: 1