You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
usingstatic System.Console;namespace PythonConsoleRedirectTest;publicstaticclassConsoleOutput{publicstaticvoidConsoleOut(){
Out.WriteLine("This is a message from 'Console.Out.WriteLine'.");}publicstaticvoidConsoleError(){
Error.WriteLine("This is a message from 'Console.Error.WriteLine'.");}}
And then try to call it within Python with:
importosimportioimportsysfromcontextlibimportredirect_stdout, redirect_stderrfrompythonnetimportloadload('coreclr')
definit_dlls() ->None:
importclrdll_path=os.path.join(
'..', 'PythonConsoleRedirectTest', 'bin', 'Release', 'net7.0')
clr.AddReference(os.path.join(dll_path, 'PythonConsoleRedirectTest'))
defexecute_csharp() ->None:
fromPythonConsoleRedirectTestimportConsoleOutputconsole_error=Nonewithredirect_stderr(io.StringIO()) asferr:
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.
This discussion was converted from issue #2346 on March 19, 2024 17:54.
Heading
Bold
Italic
Quote
Code
Link
Numbered list
Unordered list
Task list
Attach files
Mention
Reference
Menu
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Environment
Details
Hi all,
I'm currently trying to capture the output of C#'s
Console.Error
usingredirect_stderr(io.StringIO())
in Python so that I can format the text within python.If I have the following C# class:
And then try to call it within Python with:
The current out put of this is:
But I would expect it to be the following if the redirection was working as expected:
I may be missing something with how the IO streams work between C# and Python so and advice would be appreciated.
Beta Was this translation helpful? Give feedback.
All reactions