How to get a useful exception message from decimal in python 3? - python-3.x

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

Related

AttributeError: module 'torch._six' has no attribute 'PY37'

I have the newest torch installed, and my CUDA version is 11.7, so I chose the closest one torch1.12.1+cu116. However, it does not have PY3 or PY37... Can anyone help me with that? The code that I need to use has PY37 and I don't know how to make the code run...
>>> import torch
>>> torch.__version__
'1.12.1+cu116'
>>> torch._six.PY3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'torch._six' has no attribute 'PY3'
>>> torch._six.PY37
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'torch._six' has no attribute 'PY37'

how to pass command args to python scripts when the args contains the Single quotes and Double quotation marks?

import sys
import json
if __name__ == '__main__':
print(sys.argv)
print(json.loads(sys.argv[1]))
result:
(env) λ python main.py '["br_V1R22C00RR1_bugfix"]'
['main.py', "'[br_V1R22C00RR1_bugfix]'"]
Traceback (most recent call last):
File "C:\Users\x\PycharmProjects\GaussClientUpgrade\main.py", line 30, in <module>
print(json.loads(sys.argv[1]))
File "c:\users\x\appdata\local\programs\python\python39\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "c:\users\x3\appdata\local\programs\python\python39\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "c:\users\x\appdata\local\programs\python\python39\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I want to pass a string like '["br_V1R22C00RR1_bugfix"]', do not eliminate the ' and ", it's a json.dumps(list)'s result, i use json.loads to load the '["br_V1R22C00RR1_bugfix"]'.
but how can I pass the string i want?
This problem has no relation with the program language, and e.g. can happen in java too.
It's because of different argument handling between bash and dos.
In linux:
[root#clarence lib]# python test.py \"['br']\"
"[br]"
[br]
[root#clarence lib]# python test.py '["br"]'
["br"]
['br']
[root#clarence lib]# python test.py [\"br\"]
["br"]
['br']
[root#clarence lib]# python test.py "[\"br\"]"
["br"]
['br']
[root#clarence lib]# python test.py "['br']"
['br']
Traceback (most recent call last):
File "test.py", line 7, in <module>
print(json.loads(sys.argv[1]))
File "/usr/lib64/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/usr/lib64/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib64/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 2 (char 1)
[root#clarence lib]# python test.py "[\"br\"trer't]"
["br"trer't]
Traceback (most recent call last):
In windows dos:
(env) λ python test.py \"['br']\"
"['br']"
['br']
(env) λ python test.py '["br"]'
'[br]'
Traceback (most recent call last):
File "C:\Users\clarence\Desktop\test.py", line 7, in <module>
print(json.loads(sys.argv[1]))
(env) λ python test.py [\"br\"]
["br"]
['br']
(env) λ python test.py "[\"br\"]"
["br"]
['br']
(env) λ python test.py "['br']"
['br']
Traceback (most recent call last):
python test.py '["br"]' in bash can run successfully, but not in dos.

AttributeError: module 'readline' has no attribute 'set_completer_delims'

>>> import pdb
>>> x = [1,2,3,4,5]
>>> y = 6
>>> z = 7
>>> r1 = y+z
>>> r1
13
>>> r2 = x+y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list
>>> pdb.set_trace()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.6/pdb.py", line 1585, in set_trace
Pdb().set_trace(sys._getframe().f_back)
File "/usr/lib/python3.6/pdb.py", line 156, in __init__
readline.set_completer_delims(' \t\n`##$%^&*()=+[{]}\\|;:\'",<>?')
AttributeError: module 'readline' has no attribute 'set_completer_delims'
>>>
Whats problem? run python3.6 an error occurred
I just try to pdb on Cygwin.
(Note that other lib is okay)
In my case the problem was fixed by installing pyreadline:
pip install pyreadline
Please try it.
More info: https://github.com/winpython/winpython/issues/544

New line on error message in KeyError - Python 3.3

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

Python http.client.Incomplete Read(0 bytes read) error

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

Resources