IronLanguages / IronLanguages/ironpython3

Print Output Redirection not fully works

Open
#1,863 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C#
Stars
2.8k
Forks
316
Avg merge
1d 9h
Merged PRs (30d)
1

Description

Prerequisites

The issue tracker is used to report bugs and request new features, NOT to ask questions.

Questions should be posted in Discussions or to the users mailing list which can be accessed at
https://ironpython.groups.io/g/users.

  • [ YES ] Are you running the latest version?
  • [ YES ] Are you reporting to the correct repository?
  • [ YES ] Did you perform a cursory search?
Description

I have a Python Script running from C#, by calling a def function inside a class of a file.
The Console prints out the print(...) values, but the Function i want to be called (StreamWriter custom from GPT) is not being called. By C# Code Running with Console.WriteLine it calls the function properly.

Steps to Reproduce

Code i used (Runner class C#):

internal Runner(StreamWriter? writer = null, MemoryStream? msPython = null, Action<object?, MyEvtArgs<string>>? tboxwritepython = null)
{
    _verbose = Statics._variables.verbose;
    if (writer != null)
    {
        _writer = writer;
        _verbose = false;
    }
    if (msPython != null || tboxwritepython != null)
    {
        if (msPython == null)
            msPython = new();
        if (tboxwritepython == null)
            tboxwritepython = new((obj1, tar1) => { Console.WriteLine(tar1.ToString()); });
        _pywriterms = msPython;
        _pywriter = new(msPython);
        _pywriter.StringWritten += new EventHandler<MyEvtArgs<string>>(tboxwritepython);
    }
}

internal object? InvokePythonMethod(string classname, string methodname, params object[] args)
{
    if (_pythonScripts.Count == 0)
        throw new InvalidOperationException("No Python script added.");

    var runtime = Python.CreateRuntime();

    if (_pywriter != null)
    {
        runtime.IO.SetOutput(_pywriterms, _pywriter);
        runtime.IO.SetErrorOutput(_pywriterms, _pywriter);
    }

    runtime.IO.RedirectToConsole();
    var engine = Python.GetEngine(runtime);

    var searchPaths = engine.GetSearchPaths();
    if (!searchPaths.Contains(Environment.CurrentDirectory))
        searchPaths.Add(Environment.CurrentDirectory);
    engine.SetSearchPaths(searchPaths);

    var scope = engine.CreateScope();
    foreach (var script in _pythonScripts)
    {
        engine.ExecuteFile(script, scope);
    }

    dynamic pyClass = scope.GetVariable(classname);
    dynamic pyInstance = engine.Operations.CreateInstance(pyClass);
    dynamic pyMethod = engine.Operations.GetMember(pyInstance, methodname);
    
    var result = pyMethod.Call(args);
    return result;
}

My ViewModel Code is this:

public ICommand RunScript => new cmdHandler(() =>
{
    PreRun();
    Task.Run(() =>
    {
        for (int i = 0; i < ParallelCount; i++)
        {
            Runner run = new(
                writer: new ObservableStreamWriter(new MemoryStream(), ((str) => UpdateOutput(str, i))),
                tboxwritepython: new(((obj1, tar1) => UpdateOutput(tar1.Value, i))));
            Running(run, i);
        }
    });
}, () => true);

private void UpdateOutput(string outp, int index, Results result = Results.INFO, string DrawRef = "LOG MESSAGE")
{
    UpdateLineEntry(index, new()
    {
        Message = outp,
        Drawref = DrawRef,
        Result = result
    });
}

The Python Code is this:

class testing:
    def __init__(self):
        print("Hello Init")

    def submit(self):
        print("entered text were " + self.entry.get())

    def outputing(self, Name):
        print(f"Hello {Name}")
        return "Whatsup"

Expected behavior:
Actual behavior:

And by calling then: InvokePythonMethod("testing", "outputing", "ABC");
The Function (UpdateOutput) is not being called. But with a C# Code call, it works fine.

Version Information

If you are using the ipy console program, provide output of executing ipy -VV. If it is a local build, provide also the git hash of the commit used to build IronPython. In either case, provide the type of the operating system used.

If you are using the IronPython engine embedded in a .NET application, provide the version number of the NuGet package used (or if it is a local build, the git hash of the commit used to build IronPython), and the following info:

  • .NET platform used (choice from: .NET, .NET Core, .NET Framework, Mono, Unity, Xamarin),

  • Version of the .NET platform used,

  • Operating system used,

  • Value of sys.version, from imported module sys.

  • .NET Core 8.0.11

  • Windows 11 10.0.22631

  • IronPython Version 3.4.1 (NuGet)

  • Visual Studio 2022 Version 17.12.3

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the supplied Runner and Python examples, then inspect the interaction between runtime.IO.SetOutput, runtime.IO.SetErrorOutput, and runtime.IO.RedirectToConsole in InvokePythonMethod. Trace whether print output reaches _pywriter and UpdateOutput, and document the expected versus actual callback behavior before checking the relevant IronPython I/O implementation and tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp, python
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.