-
Notifications
You must be signed in to change notification settings - Fork 766
Closed
Description
Environment
- Pythonnet version: 3.0.3
- Python version: 3.11.4
- Operating System: Windows 10 x64
- .NET Runtime: Microsoft.NETCore.App 7.0.15
Details
Hi all,
I'm currently trying to capture the output of C#'s Console.Error
using redirect_stderr(io.StringIO())
in Python so that I can format the text within python.
If I have the following C# class:
using static System.Console;
namespace PythonConsoleRedirectTest;
public static class ConsoleOutput
{
public static void ConsoleOut()
{
Out.WriteLine("This is a message from 'Console.Out.WriteLine'.");
}
public static void ConsoleError()
{
Error.WriteLine("This is a message from 'Console.Error.WriteLine'.");
}
}
And then try to call it within Python with:
import os
import io
import sys
from contextlib import redirect_stdout, redirect_stderr
from pythonnet import load
load('coreclr')
def init_dlls() -> None:
import clr
dll_path = os.path.join(
'..', 'PythonConsoleRedirectTest', 'bin', 'Release', 'net7.0')
clr.AddReference(os.path.join(dll_path, 'PythonConsoleRedirectTest'))
def execute_csharp() -> None:
from PythonConsoleRedirectTest import ConsoleOutput
console_error = None
with redirect_stderr(io.StringIO()) as ferr:
sys.stderr.write("This is a message from 'sys.stderr'.")
ConsoleOutput.ConsoleError()
console_error = ferr.getvalue()
print(f"\n{console_error}")
if __name__ == "__main__":
init_dlls()
execute_csharp()
The current out put of this is:
This is a message from 'Console.Error.WriteLine'.
This is a message from 'sys.stderr'.
But I would expect it to be the following if the redirection was working as expected:
This is a message from 'sys.stderr'.
This is a message from 'Console.Error.WriteLine'.
I may be missing something with how the IO streams work between C# and Python so and advice would be appreciated.
Metadata
Metadata
Assignees
Labels
No labels