Python 2 error:"Internal Python error in the inspect module - python

I have written this code to calculate the quadratic formula:
from numpy.lib.scimath import sqrt as csqrt
a = raw_input("a?")
b = raw_input("b?")
c = raw_input("c?")
def numcheck(x):
try:
i = float(x)
return True
except (ValueError, TypeError):
return False
if numcheck(a)==True:
a=int(a)
else:
print "a is not a number"
if numcheck(b)==True:
b=int(b)
else:
print "b is not a number"
if numcheck(c)==True:
c=int(c)
else:
print "b is not a number"
sqrt= ((b*b) - (4* (a*c)))
x_minus= (-b+(csqrt(sqrt)))/(2*a)
x_minus=str(x_minus)
x_plus= (-b-(csqrt(sqrt)))/(2*a)
x_plus=str(x_plus)
print "The solution is "+x_plus+" or "+x_minus
Never minding the rather crappy style, when the input is not a number, I get this error:
Traceback (most recent call last):
File "build\bdist.win32\egg\IPython\core\ultratb.py", line 776, in structured_traceback
File "build\bdist.win32\egg\IPython\core\ultratb.py", line 230, in wrapped
File "build\bdist.win32\egg\IPython\core\ultratb.py", line 267, in _fixed_getinnerframes
UnicodeDecodeError: 'ascii' codec can't decode byte 0xba in position 51: ordinal not in range(128)
ERROR: Internal Python error in the inspect module.
Below is the traceback from this internal error.
Unfortunately, your original traceback can not be constructed.
Can anyone tell me why this is happening and, if possible, a way to fix it? Thanks.

To do a sqrt, you can simply do this:
def sqrt(num):
return num ** 0.5
I'll try to give you more info related to your problem, but for now try to replace your sqrt with that one.

Related

How to print line number of error that is inside a function using except in Python?

I want to print an error's line number and error message in a nicely displayed way. The follow is my code, which uses linecache:
import linecache
def func():
if xx == 1:
print('ok')
try:
func()
except:
exc_type, exc_obj, tb = sys.exc_info()
f = tb.tb_frame
lineno = tb.tb_lineno
filename = f.f_code.co_filename
linecache.checkcache(filename)
line = linecache.getline(filename, lineno, f.f_globals)
print_('ERROR - (LINE {} "{}"): {}'.format(lineno, line.strip(), exc_obj))
However, this only gives where the func() is called:
ERROR - (LINE 8 ""): name 'xx' is not defined
Is there a way to print the line number where the error actually occured, which should be Line 4? Or even better, can I print Line 8 and then trace back to line 4? For example, if I do not use try - except, the code:
def func():
if xx == 1:
print('ok')
func()
will give me the following error message, which is much better to locate the error:
File "<input>", line 5, in <module>
File "<input>", line 2, in func
NameError: name 'xx' is not defined. Did you mean: 'xxx'?
You can use traceback and sys modules to get advanced traceback output like you are wishing for.
Here is an example:
import traceback
import sys
def func():
zeroDivide = 1 / 0
try:
func()
except Exception:
print(traceback.format_exc()) # This line is for getting traceback.
print(sys.exc_info()[2]) # This line is getting for the error type.
Output will be:
Traceback (most recent call last):
File "b:\abc\1234\pppp\main.py", line 10, in <module>
func()
File "b:\abc\1234\pppp\main.py", line 7, in func
zeroDivide = 1 / 0
ZeroDivisionError: division by zero
You can use the traceback module to get the line number of the error,
import traceback
def function():
try:
# code
except:
tb_list = traceback.extract_tb(sys.exc_info()[2])
line_number = tb_list[-1][1]
print("An error occurred on line:", line_number)
You can use the traceback.extract_tb() function. This function returns a list of traceback objects, each of which contain information about the stack trace. The last element of this list, tb_list[-1], holds information about the line where the exception occurred. To access the line number, you can use the second element of this tuple, tb_list[-1][1]. This value can then be printed using the print() function.
To get the line number as an int you can get the traceback as a list from traceback.extract_tb(). Looking at the last item gives you the line where the exception was raised:
#soPrintLineOfError2
import sys
import traceback
def func():
if xx == 1:
print('ok')
try:
func()
except Exception as e:
tb = sys.exc_info()[2]
ss = traceback.extract_tb(tb)
ss1 = ss[-1]
print(ss1.line)
print(ss1.lineno)
Output:
if xx == 1:
6

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"))

Python Try and Except Statements Custom and Normal Exception Output

When throwing an exception how do I get the compiler to throw my custom exception AND the compiler exception.
Here is an example of what I want to happen
def func_A(int)
try:
ans = 1 + int
print(ans)
except:
print('Oops your input was wrong')
def func_B(int)
ans = 1 + int
print(ans)
Input_A:
func_A('Hello_World')
Output_A:
'Oops your input was wrong'
Input_B:
func_B('Hello_World')
Output_B:
File "<ipython-input-5-fe7d28575c18>", line 2
def func_B(int)
^
SyntaxError: invalid syntax
Desired Output:
'Oops your input was wrong'
File "<ipython-input-5-fe7d28575c18>", line 2
def func_B(int)
^
SyntaxError: invalid syntax
Try adding a raise to the end of your except to raise the exception again, like this:
def func_A(int):
try:
ans = 1 + int
print(ans)
except:
print('Oops your input was wrong')
raise
func_A('Hello_World')
Output:
Oops your input was wrong
Traceback (most recent call last):
File "/home/ashish/s.py", line 15, in <module>
func_A('Hello_World')
File "/home/ashish/s.py", line 3, in func_A
ans = 1 + int
TypeError: unsupported operand type(s) for +: 'int' and 'str'

BitString - Can't load my value in BitStream

A simple question.
I have a <\class 'str'> (checked) with a 124 length hexa content named hexapacket.
I'm doing like this:
import bitstring
data = BitStream(hexa=hexapacket)
# My processing on bits
But it raises errors like it can't find the length etc ..
ValueError: invalid literal for int() with base 10: '0edd0e000201a9017dc0c3898000000000'
and
ValueError: Don't understand length '0edd0e000201a9017dc0c3898000000000' of token.
and
KeyError: ('0edd0e000201a9017dc0c3898000000000', 0)
Could you help to make it working ? It's the solution i wanted to parse datas.
EDIT :
I tried some debug and the output is strange, the hex() cast and the bin() cast add 0b and 0x at the start of the string and i have handle it by string = string[2:]
But it still doesn't work with BitStream from bitstring.
I precise that the original packet comes from pyshark and i casted the packet.data.data into string.
CODE :
if hexapacket.find(':') != -1:
hexapacket = ''.join(packet.split(":"))
if hexapacket.find('0x') != -1:
hexapacket = hexapacket[2:]
msgid = int(bin(int(hexapacket[:4],16))[2:-2],2)
messagetype = dict_ids[msgid]
lenoflen = int(bin(int(hexapacket[:4],16))[-2:],2)
print("ID: %d\nMSG: %s\nLoL: %d\n" % (msgid,messagetype,lenoflen))
print("My hexapacket\n%s" % hexapacket)
raw = BitStream(hex=hexapacket)
OUTPUT :
ID: 950
MSG: GameMapMovementRequestMessage
LoL: 1
My hexapacket
0ed93c0003519a418c418b050c0405fafb5a21348190b66ecc166c09f832a7324069fcd9e19ea6be654b26b42563908947857a2b3cb25ce920837262a5fb69
ERRORS:
Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/bitstring.py", line 612, in tokenparser
length = int(length)
ValueError: invalid literal for int() with base 10: '0pad:0pad:0pad:0pad:0pad:0pad:0pad:0'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "main.py", line 232, in <module>
messages = PacketProcessing().splitProcess(packet)
File "main.py", line 182, in splitProcess
data1 = raw.read('pad:%d'%datalen*8)
File "/usr/local/lib/python3.5/site-packages/bitstring.py", line 3880, in read
_, token = tokenparser(fmt)
File "/usr/local/lib/python3.5/site-packages/bitstring.py", line 622, in tokenparser
raise ValueError("Don't understand length '{0}' of token.".format(length))
ValueError: Don't understand length '0pad:0pad:0pad:0pad:0pad:0pad:0pad:0' of token.
OUTPUT of repr(hexapacket) and type(hexapacket):
'0ed93a0002118b11a8050c04053e03bcd154bb84543c9b2a7992280bddf099b126acd1e75bf274842565e499d9e0221f86c02fa26d0a859ce426e63a74'
and
<class 'str'>
ANSWER : Use BitString module for Python3.x, it's easier to cast and read data.
It should work, if you specify hex= keyword argument:
>>> import bitstring
>>> bitstring.BitStream(hex='0edd0e000201a9017dc0c3898000000000')
BitStream('0x0edd0e000201a9017dc0c3898000000000')

Condition not being evaluated as expected

I have a piece of code that acts as a listener of a button and evaluates whether some fields above this button are filled in:
def goListener(self):
if all( [self.nme.get() != "", self.dsc.get() != "", self.imp.get != ""] ):
name = self.nme.get()
desc = self.dsc.get()
while True:
try:
imp = int(self.imp.get())
break
except:
imp = int(self.imp.get())
When I run this program with different fields filled in or otherwise, it gets it right and produces the error message I ask it to with every combination except where nme and dsc are filled in but imp isn't, this produces the error message:
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1442, in __call__
return self.func(*args)
File "C:\Python33\todo.py", line 68, in goListener
imp = int(self.imp.get())
ValueError: invalid literal for int() with base 10: ''
This is running the except block by the way, which it shouldn't. Is this a problem with the evaluation, or am I missing something here?
You have:
self.imp.get != ""
You are failing to invoke the .get() method. Try:
self.imp.get() != ""
If imp = int(self.imp.get()) throws an error, calling it again outside of a try block will throw the same error.
The except block is for code that should run when there is an exception:
try:
imp = int(self.imp.get())
break
except:
print "Something bad happened"

Categories

Resources