Replies: 3 comments
-
|
I think this issue seriously needs some attention. |
Beta Was this translation helpful? Give feedback.
-
|
EDIT 12/19/23: I noticed that when running the application directly from cmd line with EDIT 1/24/24: Dug a little further and noticed that when debugging directly from VS Code & the C# dev kit extension using the internalConsole (i.e. VS Code's built-in debug console) setting, then python Since regular C# OP: I ended up putting together the below code instead of using the sample code shown in the above SO post, mostly because I wanted a global option that didn't require every python call wrapped in a context. Additionally, the sample code in that SO post will only show the console output after the python script has finished executing, while the below should print it out in real time during live execution (i.e. long running processes or while-loop infinite loops). This also seems to work when running script files via using Python.Runtime;
Console.WriteLine("Hello, World!");
Runtime.PythonDLL = "python312.dll";
PythonEngine.Initialize();
using var _ = Py.GIL();
using var scope = Py.CreateScope();
scope.Exec(
"""
import sys
class NetConsole(object):
def __init__(self, writeCallback):
self.terminal = sys.stdout
self.writeCallback = writeCallback
def write(self, message):
self.terminal.write(message)
self.writeCallback(message)
def flush(self):
# this flush method is needed for python 3 compatibility.
# this handles the flush command by doing nothing.
# you might want to specify some extra behavior here.
pass
def setConsoleOut(writeCallback):
sys.stdout = NetConsole(writeCallback)
"""
);
dynamic setConsoleOutFn = scope.Get("setConsoleOut");
var writeCallbackFn = (string message) => {
if (message != "\n")
Console.Write("[Py]: ");
Console.Write(message);
};
setConsoleOutFn(writeCallbackFn);
scope.Eval("print('hello world')");.NET Console output:
Hope this helps someone else! |
Beta Was this translation helpful? Give feedback.
-
|
Building off of @ipavel83 's answer, you can even implement stdout as a C# class to avoid embedding large strings of Python code like that. sealed class ConsoleStdio
{
public void write(string s) => Console.WriteLine(s);
// Doesn't seem to be needed in my case
//public void flush() { }
}
using var scope = Py.CreateScope();
// Redirect stdio
dynamic sys = scope.Import("sys");
sys.stdout = new ConsoleStdio();
sys.stderr = new ConsoleStdio();
// Exec the user's code
scope.Exec("print('hello world')"); |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I have successfully was able to run python script in Unity3D:
in python script with print("something") does nothing.
When I do
System.Console.SetOut(consoleOut2)I am able to successfully get output from python ofSystem.Console.WriteLine, butprint("something")still does not output anything.Beta Was this translation helpful? Give feedback.
All reactions