When a python function fails, we get a traceback listing filenames, lines, and function calls.
Is there anyway, within an except block, to pull out only these function names? I would just like a list of the successive calls that lead to the failure.
I have looked at the traceback library and have run dir() on my exception, but I don't see anything.
I took one last look at the traceback documentation and figured it out.
First, use traceback.extract_tb() to get the StackSummary. This is a list of FrameSummary objects, which themselves are tuples whose third value is the function name. In full:
try:
some_function()
except Exception as e:
tb = traceback.extract_tb(e.__traceback__)
for frame in tb:
print(frame[2])
output will be something like
<module>
some_function
another_func_called_by_some_function
...
Related
I have a stacktrace created by the faulthandler after a fatal interpreter crash. Its content looks like below:
File "/path/to/file.py", line <line-number> in <function-name>
File "/path/to/file.py", line <line-number> in <function-name>
I want to create a traceback object from this file, similar to the one from sys.exc_info() to upload it to sentry. Is there any module that will make it easier?
I will not have the scope variables, but it should be possible to capture the code object with content of the files from traceback.
For now the only solution I can think of is to create a class that will behave similar to the traceback object, but this seems like a lot of work (especially if I want the code).
In the end I have prepared my own class that behaves as a traceback object (using duck-typing). The only thing that was important to set valid f_code.co_filename and f_code.co_name and sentry client will extract the source code.
So I'm trying to make a timed function for my Discord bot with python.
So my function is as follows:
async def checkday(ctx):
while(True):
"code yada yada"
if true:
await ctx.send("hello")
await asyncio.sleep(X)
and at the bottom:
bot.loop.create_task(checkday())
However, I either get this error:
Traceback (most recent call last):
File "C:\Users\philk\Desktop\Discord Bot\testrevbot.py", line 374, in <module>
bot.loop.create_task(checkday())
TypeError: checkday() missing 1 required positional argument: 'ctx'
So I'm assuming there is an argument I'm missing here:
bot.loop.create_task(checkday())
How would I be able to fix this? I'm using Rewrite I believe, so is there a way to send messages without Context?
EDIT: I want to, for example, run the loop in checkday() every 12 hours, and if conditions are met, then to send a message.
"https://github.com/Rapptz/discord.py/blob/rewrite/examples/background_task.py" doesn't appear to work for me.
If you are doing this in a cog, you are most probably missing self as the first argument.
I am following a tutorial over at https://blog.patricktriest.com/analyzing-cryptocurrencies-python/ and I've got a bit stuck. I am tyring to define, then immediately call, a function.
My code is as follows:
def merge_dfs_on_column(dataframes, labels, col):
'''merge a single column of each dataframe on to a new combined dataframe'''
series_dict={}
for index in range(len(dataframes)):
series_dict[labels[index]]=dataframes[index][col]
return pd.DataFrame(series_dict)
# Merge the BTC price dataseries into a single dataframe
btc_usd_datasets= merge_dfs_on_column(list(exchange_data.values()),list(exchange_data.keys()),'Weighted Price')
I can clearly see that I have defined the merge_dfs_on_column fucntion and I think the syntax is correct, however, when I call the function on the last line, I get the following error:
NameError Traceback (most recent call last)
<ipython-input-22-a113142205e3> in <module>()
1 # Merge the BTC price dataseries into a single dataframe
----> 2 btc_usd_datasets= merge_dfs_on_column(list(exchange_data.values()),list(exchange_data.keys()),'Weighted Price')
NameError: name 'merge_dfs_on_column' is not defined
I have Googled for answers and carefully checked the syntax, but I can't see why that function isn't recognised when called.
Your function definition isn't getting executed by the Python interpreter before you call the function.
Double check what is getting executed and when. In Jupyter it's possible to run code out of input-order, which seems to be what you are accidentally doing. (perhaps try 'Run All')
Well, if you're defining yourself,
Then you probably have copy and pasted it directly from somewhere on the web and it might have characters that you are probably not able to see.
Just define that function by typing it and use pass and comment out other code and see if it is working or not.
"run all" does not work.
Shutting down the kernel and restarting does not help either.
If I write:
def whatever(a):
return a*2
whatever("hallo")
in the next cell, this works.
I have also experienced this kind of problem frequently in jupyter notebook
But after replacing %% with %%time the error resolved. I didn't know why?
So,after some browsing i get that this is not jupyter notenook issue,it is ipython issueand here is the issue and also this problem is answered in this stackoverflow question
To print a backtrace in python on can use the following code:
import traceback
....
traceback.print_stack()
However, I need the backtrace to be used as a string for a logger, something like this:
logger.debug(traceback.print_stack())
which, in this case, does not work. How to most simply get the backtrace to the logger?
The traceback module is full of "format" functions which docuemtnation you can see here https://docs.python.org/3/library/traceback.html
One of which is the format_stack - just pass it a Python frame object, o(by default it uses the current frame) - and it returns you a list of strings, each with the file path and line content of the running position:
logger.debug("\n".join(traceback.format_stack()) )
Or, if you have an exception traceback object, which you can retrieve with a call to sys.last_traceback , you simply pass it's tb_frame attribute to the format_stack function:
logger.debug("\n".join(traceback.format_stack(sys.last_traceback().tb_frame)) )
The simple way of logging the traceback if an exception exists:
logger.debug(traceback.format_exc())
https://docs.python.org/3/library/traceback.html
I'm learning Python 3 and trying to write a script that will copy a directory. I'm using shutil.copytree. From the Python documentation it says:
If exception(s) occur, an Error is raised with a list of reasons.
This exception collects exceptions that are raised during a multi-file
operation. For copytree(), the exception argument is a list of
3-tuples (srcname, dstname, exception).
In the example they do this:
except Error as err:
errors.extend(err.args[0])
Here is my script:
def copyDirectory(src, dest):
errors = []
try:
shutil.copytree(src, dest)
except Error as err:
errors.extend(err.args[0])
source="C:/Users/MrRobot/Desktop/Copy"
destination="C:/Users/MrRobot/Desktop/Destination"
copyDirectory(source, destination)
moveDirectory(destination,"I:/")
Questions:
How do you properly catch an exception that might occur when using shutil.copytree (assuming my above script is incorrect)?
How then would you view the errors that occurred, would I loop through the errors array?
You need to either include the module name when you catch the exception:
except shutil.Error as err:
Or import it explicitly:
from shutil import copytree, Error
# the rest of your code...
try:
copytree(src, dest)
except Error as err:
errors.extend(err.args[0])
To view the traceback and exception information, you have a few options:
Don't catch the exception. Your script will be halted and all the error information will be printed.
If you want the script to continue, then you're really asking a duplicate of this SO question. I would reference that question; the accepted answer is written very well.
And by the way, you should avoid calling it an array. This particular exception object has a list of tuples, and arrays are an entirely different data structure.
You can use OSError to handle it :
import shutil
def removeDirectory(directory):
try:
shutil.rmtree(directory)
except OSError as err:
print(err)
removeDirectory('PathOfDirectoryThatDoesntExist')
OUTPUT :
[Errno 2] No such file or directory:
'./PathOfDirectoryThatDoesntExist'