'If object is None' not behaving as expected - python-3.x

Writing an analytics script for facebook chats with python. The library I'm using (fbchat) sometimes returns None type objects in place of messages. I thought I could catch this with a simple
if message is None:
continue
in my loop through my message list. However, I'm still getting exceptions due to the object being None type. What am I doing wrong here?
Code snippet:
for message in messages:
#sometimes the fbchat library doesn't return a message
if message is None:
continue
#strip the line endings to not mess up the csv
message.text.replace('\n', ' ')
Exact exception:
Traceback (most recent call last):
File "collect.py", line 58, in <module>
message.text.replace('\n', ' ')
AttributeError: 'NoneType' object has no attribute 'replace'

Checking for message.text is None resolves the issue and is what I should have done in the first place.

Related

KeyError: 'document' occures when I try to use execute_script command in Python Selenium

I have simple code. Firstly I get an input from user. In target page, there is an editable div. I focus on it and insert the message that I got from user. When I focusing and inserting element I use Javascript so for using Javascript with Python Selenium I use execute_script command.
Code:
message = input()
message = message.replace("'","\\'")
message = message.replace('"','\\"')
browser.execute_script("setTimeout(function() {document.querySelector('._3ee1T ._3uMse ._2FVVk ._3FRCZ').focus();}, 0); document.querySelector('._3ee1T ._3uMse ._2FVVk ._3FRCZ').textContent = '{}'".format(message))
Error: Traceback (most recent call last): File "main.py", line 171, in <module> browser.execute_script("setTimeout(function() {document.querySelector('._3ee1T ._3uMse ._2FVVk ._3FRCZ').focus();}, 0); document.querySelector('._3ee1T ._3uMse ._2FVVk ._3FRCZ').textContent = '{}'".format(message)) KeyError: 'document'

CherryPy encoding: bool object not iterable

Hello,
I am using CherryPy to host the gui of an application that takes json files from qualtrics and drops them in a mysql server.
The code seems to work for most surveys but for some I get the following error:
Traceback (most recent call last):
File "C:\Users\jam66\AppData\Local\Programs\Python\Python37-32\lib\site-packages\cherrypy\_cprequest.py", line 627, in respond
self._do_respond(path_info)
File "C:\Users\jam66\AppData\Local\Programs\Python\Python37-32\lib\site-packages\cherrypy\_cprequest.py", line 686, in _do_respond
response.body = self.handler()
File "C:\Users\jam66\AppData\Local\Programs\Python\Python37-32\lib\site- packages\cherrypy\lib\encoding.py", line 264,
in __call__ct.params['charset'] = self.find_acceptable_charset()
File "C:\Users\jam66\AppData\Local\Programs\Python\Python37-32\lib\site- packages\cherrypy\lib\encoding.py", line 173, in find_acceptable_charset
if encoder(self.default_encoding):
File "C:\Users\jam66\AppData\Local\Programs\Python\Python37-32\lib\site-packages\cherrypy\lib\encoding.py", line 114, in encode_string
for chunk in self.body:
TypeError: 'bool' object is not iterable
Any help on beginning to understand this issues is appreciated
My guess is that some of your exposed methods are returning a boolean. You have to return a string or an iterable. Unless you are using the json tool, in that case the dictionary to string is handled by the tool.
As a way to debug it, just print or log the value that would will be returned, verify the type with the type function.

Uncatchable Null Byte csv.Error Exception

I'm trying to catch a Null Byte Exception in the last line of a CSV file:
def Catch(csv_filename):
with open(csv_filename,'r+') as File:
File_reader = csv.reader(File,delimiter="\t",dialect='excel-tab')
a = []
for row in File_reader:
try:
a.append(row)
except csv.Error:
return "Error"
Catch("/../DataLogger.csv")
but an _csv.Error is raised:
Traceback (most recent call last):
File "/../test.py", line 21, in <module>
Catch("/../DataLogger.csv")
File "/../test.py", line 13, in Catch
for row in File_reader:
_csv.Error: line contains NULL byte
I don't get why the exception is not catched with the function.
I'm using python 3.4
that's because the exception occurs as soon as your code reaches the for statement.
No exception can happen in the a.append line, the csv module does its job in the iteration of the for loop.
Once you know that, the fix is trivial:
try:
for row in File_reader:
a.append(row)
except csv.Error:
return "Error"
note that one could be tempted to use direct conversion to list: a = list(File_reader) but since the exception would take place in the list conversion, a wouldn't be filled, which would be a nuisance if the start of the file contains useful data you want to read (but since you're returning an error string, it doesn't seem to matter here)
def Catch(csv_filename):
with open(csv_filename,'r+') as File:
try:
File_reader = csv.reader(File,delimiter="\t",dialect='excel-tab')
a = []
for row in File_reader:
a.append(row)
except csv.Error
return "Error"
Catch("/../DataLogger.csv")
The whole parsing has to be inside Try/catch, instead of only a.append.

Getting Python error, "TypeError: 'NoneType' object is not callable" SOMETIMES

Not very new to programming or to python but incredibly green to using pyunit. Need to use it for my new job and I keep getting this error but only sometimes when it is run. My code below.
import unittest
from nose_parameterized import parameterized
from CheckFromFile import listFileCheck, RepresentsFloat
testParams = listFileCheck()
class TestSequence(unittest.TestCase):
#parameterized.expand(testParams)
def test_sequence(self, name, a, b):
if RepresentsFloat(a):
self.assertAlmostEqual(a,b,2)
else:
self.assertEqual(a,b)
if __name__ == '__main__':
unittest.main()
What is happening here is that my test case is pulling a method listFileCheck from another class. What it does is it reads values from the serial port communicating with the control board and compares them with a calibration file. It puts the control board values in an MD array along with the calibration file values. These values can be either str, int, or float.
I used the test case to compare the values to one another however I keep getting this error but only sometimes. After every 3rd or so run it fails with this error.
Error
Traceback (most recent call last):
File "C:\Python34\lib\unittest\case.py", line 57, in testPartExecutor
yield
File "C:\Python34\lib\unittest\case.py", line 574, in run
testMethod()
TypeError: 'NoneType' object is not callable
Process finished with exit code 0
Anyone know why I might be getting this error on occasion?

NameError and ValueError in Python

Why is python shell throwing a NameError where as windows console a ValueError?
def PrintArgs(*arg):
list = ['1','2']
for i in arg:
try:
print(list[int(i)])
except ValueError:
print('Please enter integer value')
except NameError:
print('Name Error')
if __name__ == '__main__':
PrintArgs(*sys.argv[1:])
Providing the following arguments to Windows Console gives this output:
Here is how I call the code in windows console:
C:\>C:\Python34\python C:\Users\User\Documents\PYTest\Test.py 0 a
1
Please enter integer value
Providing the following arguments to Python Shell does not display the cusom error for NameError as mentioned in the code above, but mentions the following error:
PrintArgs(0,a)
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
PrintArgs(0,a)
NameError: name 'a' is not defined
In the code example you've provided you define a list i, then you iterate over a collection called list you never initiated, and assign the values in this list to i, thus dropping the original value. I guess you only provided a part of your code, please provide a minimum working example.
If I try to reproduce your problem, I only get a type error, for iterating over a list which is not initialized.

Resources