Skip to content

Add Format method to pythonexception #1031

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][].
- Added support for Jetson Nano.
- Added support for __len__ for .NET classes that implement ICollection
- Added `object.GetRawPythonProxy() -> PyObject` extension method, that bypasses any conversions
- Added PythonException.Format method to format exceptions the same as traceback.format_exception

### Changed

Expand Down
36 changes: 36 additions & 0 deletions src/embed_tests/TestPythonException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,5 +54,41 @@ public void TestPythonErrorTypeName()
Assert.That(ex.PythonTypeName, Is.EqualTo("ModuleNotFoundError").Or.EqualTo("ImportError"));
}
}

[Test]
public void TestPythonExceptionFormat()
{
try
{
PythonEngine.Exec("raise ValueError('Error!')");
Assert.Fail("Exception should have been raised");
}
catch (PythonException ex)
{
Assert.That(ex.Format(), Does.Contain("Traceback").And.Contains("(most recent call last):").And.Contains("ValueError: Error!"));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if Python exceptions messages are localized. If that is the case, you need to ensure the right locale is used before performing this test.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will try and figure out if exception messages are localized.

}
}

[Test]
public void TestPythonExceptionFormatNoError()
{
var ex = new PythonException();
Assert.AreEqual(ex.StackTrace, ex.Format());
}

[Test]
public void TestPythonExceptionFormatNoTraceback()
{
try
{
var module = PythonEngine.ImportModule("really____unknown___module");
Assert.Fail("Unknown module should not be loaded");
}
catch (PythonException ex)
{
// ImportError/ModuleNotFoundError do not have a traceback when not running in a script
Assert.AreEqual(ex.StackTrace, ex.Format());
}
}
}
}
42 changes: 42 additions & 0 deletions src/runtime/pythonexception.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Runtime.CompilerServices;
using System.Text;

namespace Python.Runtime
{
Expand Down Expand Up @@ -145,6 +146,47 @@ public string PythonTypeName
get { return _pythonTypeName; }
}

/// <summary>
/// Formats this PythonException object into a message as would be printed
/// out via the Python console. See traceback.format_exception
/// </summary>
public string Format()
{
string res;
IntPtr gs = PythonEngine.AcquireLock();
try
{
if (_pyTB != IntPtr.Zero && _pyType != IntPtr.Zero && _pyValue != IntPtr.Zero)
{
Runtime.XIncref(_pyType);
Runtime.XIncref(_pyValue);
Runtime.XIncref(_pyTB);
using (PyObject pyType = new PyObject(_pyType))
using (PyObject pyValue = new PyObject(_pyValue))
using (PyObject pyTB = new PyObject(_pyTB))
using (PyObject tb_mod = PythonEngine.ImportModule("traceback"))
{
var buffer = new StringBuilder();
var values = tb_mod.InvokeMethod("format_exception", pyType, pyValue, pyTB);
foreach (PyObject val in values)
{
buffer.Append(val.ToString());
}
res = buffer.ToString();
}
}
else
{
res = StackTrace;
}
}
finally
{
PythonEngine.ReleaseLock(gs);
}
return res;
}

/// <summary>
/// Dispose Method
/// </summary>
Expand Down