I'm a beginner using python. I want to create a regular expression to capture error messages from compiler output in python. How would I do this?
for example, if the compiler output is the following error message:
Traceback (most recent call last):
File "sample.py", line 1, in <module>
hello
NameError: name 'hello' is not defined
I want to be able to only extract only the following string from the output:
NameError: name 'hello' is not defined
In this case there is only one error, however I want to extract all the errors the compiler outputs. How do I do this using regular expressions? Or if there is an easier way, I'm open to suggestions
r'Traceback \(most recent call last\):\n(?:[ ]+.*\n)*(\w+: .*)'
should extract your exception; a traceback contains lines that all start with whitespace except for the exception line.
The above matches the literal text of the traceback first line, 0 or more lines that start with at least one space, and then captures the line following that provided it starts with 1 or more word characters (which fits Python identifiers nicely), a colon, and then the rest up to the end of a line.
Demo:
>>> import re
>>> sample = '''\
... Traceback (most recent call last):
... File "sample.py", line 1, in <module>
... hello
... NameError: name 'hello' is not defined
... '''
>>> re.search(r'Traceback \(most recent call last\):\n(?:[ ]+.*\n)*(\w+: .*)', sample).groups()
("NameError: name 'hello' is not defined",)
Related
I'm currently learning how to code in python and I was trying to raise exceptions in my code to make my tool more user-friendly. However, I find the template given by Maya to be too simple and I'd like to have more control over it.
Normally, the base template looks a little like this:
raise Exception(errorTitle)
>>> Result
# Error: errorTitle
# Traceback (most recent call last):
# File "<maya console>", line 1, in <module>
# Exception: errorTitle #
It works fine, but it doesn't let you give a more detailed description of the error. What I'm trying to achieve would look a little more like this:
raise Exception(errorTitle, errorDescription)
>>> Result
# Error: errorTitle
# errorDescription
# Traceback (most recent call last):
# File "<maya console>", line 1, in <module>
# Exception: errorTitle #
I also tried putting the errorDescription into errorTitle by adding a new line to the string, but since errorTitle is repeated twice, it becomes confusing quickly when trying to sort errors.
I know you can't really use multiple arguments in the raise function, so I was wondering if there was an error template in Maya I could reference instead of raising an error.
Alternatively, is there a way to create my own error template? If I can reuse the Traceback function and change the script bar color, it might be easier to just do that.
Thanks in advance!
You can get your desired result just like that:
>>> raise Exception("Error Title\nError description that explains the problem")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception: Error Title
Error description that explains the problem
Or you may want to declare your custom exception class:
class YourException(Exception):
def __init__(self, title, description):
super(YourException, self).__init__(title + "\n" + description)
and then you can use your original syntax:
>>> raise YourException("Error Title", "Error description that explains the problem")
File "<stdin>", line 1, in <module>
__main__.YourException: Error Title
Error description that explains the problem
I'm trying to write a nice error handler for my code, so that when it fails, the logs, traceback and other relevant info get emailed to me.
I can't figure out how to take an exception object and extract the traceback.
I find the traceback module pretty confusing, mostly because it doesn't deal with exceptions at all. It just fetches some global variables from somewhere, assuming that I want the most recent exception. But what if I don't? What if I want to ignore some exception in my error handler? (e.g. if I fail to send me email and want to retry.)
What I want
import traceback as tb
# some function that will fail after a few recursions
def myfunc(x):
assert x > 0, "oh no"
return myfunc(x-1)
try:
myfunc(3)
except Exception as e:
traceback_str = tb.something(e)
Note that tb.something takes e as an argument.
There's lots of questions on Stack Overflow about using the traceback module to get a traceback string. The unique thing about this question is how to get it from the caught exception, instead of global variables.
Result:
traceback_str contains the string:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in myfunc
File "<stdin>", line 3, in myfunc
File "<stdin>", line 3, in myfunc
File "<stdin>", line 2, in myfunc
AssertionError: oh no
Note that it contains not just the most recent function call, but the whole stack, and includes the "AssertionError" at the end
The correct function for tb.something(e) is
''.join(tb.format_exception(None, e, e.__traceback__))
I have a list.txt where every line has a different hex string. So I want to choose a line and convert the specific line in ascii. So I have written this code:
import codecs
f=open('list.txt')
lines=f.readlines()
var=lines[25]
print(var)
print( codecs.decode("{var}", "hex") )
The specific var = 2d560d4b0618203249312a310d5f541f295c3f0f25235c2b20037d1600f3
when I execute this command:
print( codecs.decode("2d560d4b0618203249312a310d5f541f295c3f0f25235c2b20037d1600f3", "hex") ) I get the result.
But when I try to put the var variable I get this error:
Traceback (most recent call last): File "/usr/local/lib/python3.7/encodings/hex_codec.py", line 19, in ee4'hex_decode return (binascii.a2b_hex(input), len(input))binascii.Error: Odd-length string
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "main.py", line 8, in <module>
print( codecs.decode("{var}", "hex") )
binascii.Error: decoding with 'hex' codec failed (Error: Odd-length string) `
The new lines were being included in the string. Here is a working version that strips the white-space characters.
import codecs
f=open('list.txt')
lines=f.readlines()
var=lines[25].strip()
print(codecs.decode(var, "hex"))
Example code:https://onlinegdb.com/S1ZVk4jiH
I want to validate a 2- or 3-letter iso code, but also allow it to be empty (so it can be 0, 2, or 3 characters).
'\w{2,3}|'
This works locally and also on http://www.freeformatter.com/xml-validator-xsd.html. However, when I try running it on an ubuntu machine, I get the following error:
>>> import urllib2
>>> from lxml import etree
>>> xsd_url = 'https://s3-us-west-1.amazonaws.com/premiere-avails/movie.xsd.xml'
>>> xsd_contents = urllib2.urlopen(xsd_url).read()
>>> xmlschema_doc = etree.fromstring(xsd_contents)
>>> xmlschema=etree.XMLSchema(xmlschema_doc)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "xmlschema.pxi", line 102, in lxml.etree.XMLSchema.__init__ (src/lxml/lxml.etree.c:168126)
lxml.etree.XMLSchemaParseError: Element '{http://www.w3.org/2001/XMLSchema}pattern':
The value '\w{2,3}|' of the facet 'pattern' is not a valid regular expression., line 58
What would be a better regex pattern for this? (\w{2,3})? also fails with xsd, so it needs to be something else.
I have a file that gets generated by :
excerpt:
group0 = ['ParentPom']
group1 = ['Commons','http', 'availability','ingestPom','abcCommons','solrIndex','123Service']
...
group10=['totalCommons','Generator']
How can I include this in my python script, tried import but no luck
>>> import dependencies_custom
>>> print (group2[0])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'group2' is not defined
In the import form you're using, you should be able to access the groups by
dependencies_custom.group2[0]
type notation. If you want just use just group2[0] notation, try using:
from dependencies_custom import *