I am using Python 3.3 through the IDLE. While running a code that looks like:
raise KeyError('This is a \n Line break')
it outputs:
Traceback (most recent call last):
File "test.py", line 4, in <module>
raise KeyError('This is a \n Line break')
KeyError: 'This is a \n Line break'
I would like it to output the message with the line break like this:
This is a
Line Break
I have tried to convert it to a string before or using os.linesep but nothing seems to work. Is there any way I can force the message to be correctly shown on the IDLE?
If I raise an Exception (instead of KeyError) then the output is what I want, but I would like to still raise a KeyError if possible.
You problem has nothing to do with IDLE. The behavior you see is all from Python. Running current repository CPython interactively, from a command line, we see the behavior you reported.
Python 3.7.0a2+ (heads/pr_3947:01eae2f721, Oct 22 2017, 14:06:43)
[MSC v.1900 32 bit (Intel)] on win32
>>> raise KeyError('This is a \n Line break')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'This is a \n Line break'
>>> s = 'This is a \n Line break'
>>> s
'This is a \n Line break'
>>> print(s)
This is a
Line break
>>> raise Exception('This is a \n Line break')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception: This is a
Line break
>>> raise IndexError(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: This is a
Line break
>>> try:
... raise KeyError('This is a \n Line break')
... except KeyError as e:
... print(e)
'This is a \n Line break'
>>> try:
... raise KeyError('This is a \n Line break')
... except KeyError as e:
... print(e.args[0])
This is a
Line break
I don't know why KeyError acts differently from even IndexError, but printing e.args[0] should work for all exceptions.
EDIT
The reason for the difference is given in this old tracker issue, which quotes a comment in the KeyError source code:
/* If args is a tuple of exactly one item, apply repr to args[0].
This is done so that e.g. the exception raised by {}[''] prints
KeyError: ''
rather than the confusing
KeyError
alone. The downside is that if KeyError is raised with an
explanatory
string, that string will be displayed in quotes. Too bad.
If args is anything else, use the default BaseException__str__().
*/
This section appears in the KeyError_str object definition in Objects/exceptions.c of the Python source code.
I will mention your issue as another manifestation of this difference.
There is a way to get the behavior you want: Simply subclass str and override __repr__:
class KeyErrorMessage(str):
def __repr__(self): return str(self)
msg = KeyErrorMessage('Newline\nin\nkey\nerror')
raise KeyError(msg)
Prints:
Traceback (most recent call last):
...
File "", line 5, in
raise KeyError(msg)
KeyError: Newline
in
key
error
Related
With Python 2, creating a Decimal with an invalid string produces a useful error message:
>>> import decimal
>>> decimal.Decimal('spam')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/decimal.py", line 547, in __new__
"Invalid literal for Decimal: %r" % value)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/decimal.py", line 3872, in _raise_error
raise error(explanation)
decimal.InvalidOperation: Invalid literal for Decimal: 'spam'
While Python 3 produces a not-so-helpful message:
>>> import decimal
>>> decimal.Decimal('spam')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
Is there any way to get a useful message like "Invalid literal for Decimal: 'spam'" from the exception in Python 3?
I'm using Python 2.7.15 and Python 3.7.2, both on darwin.
Addenda:
It looks like Python 2 once had a not-very-helpful message for decimal.InvalidOperation: https://bugs.python.org/issue1770009
This situation looks analogous but most of it goes over my head: https://bugs.python.org/issue21227
You could monkey-patch the decimal module.
import decimal
def safe_decimal(something):
try:
funct_holder(something)
except Exception as e:
new_errror = Exception("Hey silly that's not a decimal, what should I do with this? {}".format(something))
raise new_errror from None
funct_holder = decimal.Decimal
decimal.Decimal = safe_decimal
Then you could use the monkey patched version as so
>>> decimal.Decimal('hello')
Traceback (most recent call last):
File "<input>", line 12, in <module>
File "<input>", line 6, in safe_decimal
Exception: Hey silly that's not a decimal, what should I do with this? hello
I am having some issues running my program. I have a "masterfile" that has a list of ips on a \n like so but I keep getting this error message:
68.x.0.56
68.x.0.53
I'm not sure what exactly the problem is, but I've been searching forums and other stackoverflow help, but can't seem to determine what the issue is.
def dns_resolver(subdomains):
print('\n\n########## Checking Subdomains for DNS Resolutions ##########\n')
queries = []
with open ('masterfile', 'r') as f:
domains = f.read().splitlines()
for i in domains:
try:
resp = socket.gethostbyname(i)
print(resp)
queries.append((i, resp))
except socket.error:
pass
return queries
Traceback (most recent call last):
File "/usr/lib/python3.6/encodings/idna.py", line 165, in encode
raise UnicodeError("label empty or too long")
UnicodeError: label empty or too long
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "subdomain-hunter.py", line 170, in <module>
main()
File "subdomain-hunter.py", line 59, in main
enumerate(DOMAIN)
File "subdomain-hunter.py", line 120, in enumerate
resolvediff = dns_resolver(diff)
File "subdomain-hunter.py", line 142, in dns_resolver
resp = socket.gethostbyname(i)
UnicodeError: encoding with 'idna' codec failed (UnicodeError: label empty or too long)
I wrote the following code that works with python3
try:
json.loads(text)
except json.decoder.JSONDecodeError:
(exception handling)
However, if I use python2, when json.loads throws the exception I get:
File "mycode.py", line xxx, in function
except json.decoder.JSONDecodeError:
AttributeError: 'module' object has no attribute 'JSONDecodeError'
And actually, https://docs.python.org/2/library/json.html doesn't mention any JSONDecodeError exception, while https://docs.python.org/3/library/json.html does.
How can I have the code running both with python 2 and 3?
In Python 2 json.loads raises ValueError:
Python 2.7.9 (default, Sep 17 2016, 20:26:04)
>>> json.loads('#$')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
You can try to use json.decoder.JSONDecodeError. If it fails you will know that you need to catch ValueError:
try:
json_parse_exception = json.decoder.JSONDecodeError
except AttributeError: # Python 2
json_parse_exception = ValueError
Then
try:
json.loads(text)
except json_parse_exception:
(exception handling)
Will work in either case.
I have seen this error on the forum and read through the responses yet I still don't understand what it is or how to address it. I'm scraping data from the internet from 16k links, my script scrapes similar information from each link and writes it to a .csv some of the date gets written before this error.
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 541, in _get_chunk_left
chunk_left = self._read_next_chunk_size()
File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 508, in _read_next_chunk_size
return int(line, 16)
ValueError: invalid literal for int() with base 16: b''
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 558, in _readall_chunked
chunk_left = self._get_chunk_left()
File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 543, in _get_chunk_left
raise IncompleteRead(b'')
http.client.IncompleteRead: IncompleteRead(0 bytes read)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "MoviesToDb.py", line 91, in <module>
html = r.read()
File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 455, in read
return self._readall_chunked()
File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 565, in _readall_chunked
raise IncompleteRead(b''.join(value))
http.client.IncompleteRead: IncompleteRead(17891 bytes read)
I would like to know:1) What does this error mean? 2) How do I prevent it?
try to import :
from http.client import IncompleteRead
and add this in your script :
except IncompleteRead:
# Oh well, reconnect and keep trucking
continue
requests.exceptions.ChunkedEncodingError: (‘Connection broken: IncompleteRead(0 bytes read)’, IncompleteRead(0 bytes read)).
It is because the server of http protocal is 1.0 version,while python use 1.1 version. The solution is to assign the protocal version of client, like this
Python3 Version please add:
> import http.client
> http.client.HTTPConnection._http_vsn = 10
> http.client.HTTPConnection._http_vsn_str = 'HTTP/1.0'
Python2 Version please add:
> import http.client
> http.client.HTTPConnection._http_vsn = 10
> http.client.HTTPConnection._http_vsn_str = 'HTTP/1.0'
See the reference How to deal with "http.client.IncompleteRead: IncompleteRead(0 bytes read)" problem
I'm getting error for line 1 not sure what the problem is
Traceback (most recent call last):
File "python", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'mars' is not defined
Here's the code:
x = int(input("what is the fourth planet in the solar system: "))
if x == mars:
print ("correct")
else print ("incorrect")
You forgot the quotes around mars just like this 'mars'