Reputation: 137
I am trying to make a function to help me debug. When I do the following:
s = traceback.format_stack()[-2]
print(s)
I get a console output something like:
File "/home/path/to/dir/filename.py", line 888, in function_name
How can I extract filename.py
, 888
and function_name
into separate strings? Using a regex?
Upvotes: 1
Views: 43
Reputation: 56
string = 'File "/home/path/to/dir/filename.py", line 888, in function_name'
search = re.search('File (.*), line (.*), in (.*)', string, re.IGNORECASE)
print search.group(1)
print search.group(2)
print search.group(3)
Upvotes: 1
Reputation: 141
Try with this regular expression:
File \"[a-zA-Z\/_]*\/([a-zA-Z]+.[a-zA-Z]+)", line ([0-9]+), in (.*)
you can try using this site: https://regex101.com/
Upvotes: 1
Reputation: 1040
You can try to use str.split():
>>> s = 'File "/home/path/to/dir/filename.py", line 888, in function_name'
>>> lst = s.split(',')
>>> lst
['File "/home/path/to/dir/filename.py"', ' line 888', ' in function_name']
so for the 888 and function_name, you can access them like this
>>> lst[1].split()[1]
>>> '888'
and for the filename.py, you can split it by '"'
>>> fst = lst[0].split('"')[1]
>>> fst
'/home/path/to/dir/filename.py'
then you can use os.path.basename:
>>> import os.path
>>> os.path.basename(fst)
'filename.py'
Upvotes: 1