UnicodeEncodeError: trying to print win32_process (wmi module) - python

i'm trying to print all the process ( like task mannager), so i used
this code :
from ctypes import *
import wmi
c = wmi.WMI()
kernel32 = windll.kernel32
i = 0
txt = ""
for process in c.Win32_Process():
try:
txt = txt + str(process)
except:
print process
most of the process (about 144/146) pass the try and then i print all together but there are about 2 process that fail the try, and the except and raise this error while i'm trying to print them:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 178-181: ordinal not in range(128)
someone know what to do?

Related

How to return value from C program to Python script

When I try to return value from c code to python code i got error.
Traceback (most recent call last):
File "python.py", line 54, in <module>
print("\n\n\n\RESULT: ", str(result, "utf-8"))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xba in position 245: invalid start byte
in c function i try to return json string which got hex data - which I could parse in python and than make another calculation.
Example of returned string is "{"data":"0x123132"}"
In python i use
import ctypes
my_functions = ctypes.cdll.LoadLibrary("./my_functions.so")
my_functions.getJson.argtypes = (ctypes.c_char_p,)
my_functions.EthereumProcessor.restype = ctypes.c_char_p
result=my_functions.getJson()
print("\n\n\n\RESULT: ", str(result, "utf-8"))

Udacity Fundamental of programming with Python:

import urllib.request
def read_text():
quotes = open(r"C:\Users\Intel\Google Drive\Udacity\Full Stack\AbdoulCoverLetter.txt")
contents_of_files = quotes.read()
print(contents_of_files)
quotes.close()
check_profanity(contents_of_files)
My code is showing the following error:
UnicodeEncodeError: 'ascii' codec can't encode character '\u2022' in position 154: ordinal not in range(128)
I am not sure what is the issue. Please help..
def check_profanity(text_to_check):
with urllib.request.urlopen("http://www.wdylike.appspot.com/?q="+text_to_check) as response:
connection = response.read()
output = connection.read()
connection.close()
read_text()
I removed the bullet list and I changed the code. It is working fine now. Thanks..
import urllib.request
def read_text():
quotes = open(r"C:\Users\Intel\Google Drive\Udacity\Full Stack\AbdoulCoverLetter.txt")
contents_of_files = quotes.read()
print(contents_of_files)
quotes.close()
check_profanity(contents_of_files)
def check_profanity(text_to_check):
connection = urllib.request.urlopen("http://www.wdylike.appspot.com/?" + urllib.parse.urlencode([('q', text_to_check)]))
output = connection.read()
connection.close()
read_text()

Can't download images with python 2.7

I'm kinda new to Python. I want to download and rescale many images at once so I can use them as negative samples to train a haar cascade. Maybe I mixed some python 3.0 code in mine. I got the following error:
Traceback (most recent call last):
File "D:/!Servici/Python/Remake/negative_grab.py", line 26, in <module> store_raw_images()
File "D:/!Servici/Python/Remake/negative_grab.py", line 7, in store_raw_images
neg_image_urls = urllib2.urlopen(neg_images_link).read().decode()
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4837: ordinal not in range(128)
Process finished with exit code 1
My code:
import urllib2
import cv2
import os
def store_raw_images():
neg_images_link = 'http://image-net.org/api/text/imagenet.synset.geturls?wnid=n04335209'
neg_image_urls = urllib2.urlopen(neg_images_link).read().decode()
if not os.path.exists('neg_sample'):
os.makedirs('neg_samples')
pic_num = 1
for i in neg_image_urls.split('\n'):
try:
print(i)
urllib2.urlretrieve(i, "neg/"+str(pic_num)+'.jpg')
img = cv2.imread("neg/"+str(pic_num)+'.jpg', cv2.IMREAD_GRAYSCALE)
resize_image = cv2.resize(img, (100,100))
cv2.imwrite(("neg/")+str(pic_num)+'.jpg', resize_image)
pic_num += 1
except Exception as e:
print (str(e))
store_raw_images()
Your decode is running into errors. Try with decode('utf-8')

UnicodeDecodeError: 'ascii' codec can't decode byte 0xaa in position 2370: ordinal not in range(128) [duplicate]

This question already has an answer here:
how to interpret this error "UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 164: ordinal not in range(128)"
(1 answer)
Closed 5 years ago.
I'm writing a script in Python 3.5.3 that takes username/password combos from a file and writes them to another file. The script was written on a machine with Windows 10 and worked. However, when I tried to run the script on a MacBook running Yosemite, I got an error that has something to do with ASCII encoding.
The relevant function is this:
def buildDatabase():
print("Building database, this may take some time...")
passwords = open("10-million-combos.txt", "r") #File with user/pword combos.
hashWords = open("Hashed Combos.txt", "a") #File where user/SHA-256 encrypted pwords will be stored.
j = 0
hashTable = [[ None ] for x in range(60001)] #A hashtable with 30,000 elements, quadratic probing means size must = 2 x the final size + 1
for line in passwords:
toSearch = line
i = q = toSearch.find("\t") #The username/pword combos are formatted: username\tpassword\n.
n = toSearch.find("\n")
password = line[i:n-1] #i is the start of the password, n is the end of it
username = toSearch[ :q] + ":" #q is the end of the username
byteWord = password.encode('UTF-8')
sha.update(byteWord)
toWrite = sha.hexdigest() #password is encrypted to UTF-8, run thru SHA-256, and stored in toWrite
skip = False
if len(password) == 0: #if le(password) is 0, just skip it
skip = True
if len(password) == 1:
doModulo = ord(password[0]) ** 4
if len(password) == 2:
doModulo = ord(password[0]) * ord(password[0]) * ord(password[1]) * ord(password[1])
if len(password) == 3:
doModulo = ord(password[0]) * ord(password[0]) * ord(password[1]) * ord(password[2])
if len(password) > 3:
doModulo = ord(password[0]) * ord(password[1]) * ord(password[2]) * ord(password[3])
assignment = doModulo % 60001
#The if block above gives each combo an assignment number for a hash table, indexed by password because they're more unique than usernames
successful = False
collision = 0
The error is as follows:
Traceback (most recent call last):
File "/Users/connerboehm/Documents/Conner B/PythonFinalProject.py", line 104, in <module>
buildDatabase()
File "/Users/connerboehm/Documents/Conner B/PythonFinalProject.py", line 12, in buildDatabase
for line in passwords:
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xaa in position 2370: ordinal not in range(128)
What's happening here? I haven't gotten this error before on Windows, and I can't see any problem with my attempt to encode into UTF-8.
Edit: Notepad encodes in ANSI. Changing the encoding (just copying and pasting the data to a new .txt file) to UTF-8 solved the problem.
Your program doesn't say what codec is used in the file "10-million-combos.txt", so Python is in this case trying to decode it as ASCII. 0xaa isn't an ASCII ordinal so that failed. Identify what codec is used in your file and pass that in the encoding parameter for open.

UnicodeEncodeError when running Json

Im getting a Unicode error when running this test script.
import urllib
import json
movieTitle = "Bee Movie"
title = movieTitle.replace(" ", "+")
year = ""
omdbAPI = "http://www.omdbapi.com/?t={}&y={}&plot=short&r=json".format(
title, year)
print (omdbAPI)
response = urllib.urlopen(omdbAPI)
data = json.loads(response.read())
valid_data = data["Response"]
print ("This data is: " + valid_data)
if valid_data == "True":
print data["Title"]
print data["Year"]
print data["Plot"]
print data["Rated"]
print data["Released"]
print data["Runtime"]
print data["Genre"]
print data["Director"]
print data["Writer"]
print data["Actors"]
print data["Language"]
print data["Country"]
print data["Awards"]
print data["Poster"]
print data["Metascore"]
print data["imdbRating"]
print data["imdbVotes"]
print data["imdbID"]
print data["Type"]
print data["Response"]
elif valid_data == "False":
print ("This data is: " + valid_data)
else:
raise ValueError("The information was not found")
Error :
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 19: ordinal not in range(128)
I guess its because one off the actors seams to have a é character.
I figured out that I could put .encode('utf8') after print data["Actors"] but it don't seams like the smartest thing to do.
I mean a random letter could occur on more places then on actor. And seams odd to go put .encode('utf8') after every instance
UPDATE :
Traceback (most recent call last):
File "/Volumes/postergren_projectDrive/Projekt/programmingSandbox/python/courses/udacity/Programming Foundations with Python/moveis/Advance/media.py", line 25, in <module>
print data["Actors"]
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 19: ordinal not in range(128)
[Finished in 0.1s with exit code 1]
[shell_cmd: "python" -u "/Volumes/postergren_projectDrive/Projekt/programmingSandbox/python/courses/udacity/Programming Foundations with Python/moveis/Advance/media.py"]
[dir: /Volumes/postergren_projectDrive/Projekt/programmingSandbox/python/courses/udacity/Programming Foundations with Python/moveis/Advance]
[path: /usr/bin:/bin:/usr/sbin:/sbin]
Try this at the begining of your code:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
You can do this:
for key in data.keys()
data[key] = data[key].encode('utf8')

Categories

Resources