Run Python and C# together

Asked

Viewed 1,943 times

6

How can I in C# import, ie, execute some script in another language (Python)?

Example: If you write "R" in a C#program, it executes a file if called ApertouR.py.

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site.

3 answers

4

Has the Python.NET and should be the most appropriate. In some cases you can use the Ironpython. This way the two languages can work on the same platform and coexist.

There are other ways, but I think very gambiarra. One of them is to call the interpreter externally as a normal application. A lot can go wrong in this. It is a valid option, but it is not the most reliable.

It would be nice to think if you really need this, if you don’t have a better solution. We can’t help much more because the question doesn’t tell you the scenario where it will be used. You may not even need Python.

4


There is no way to import, both languages have no relation, now be want to trigger the execution of a Python through a script c# so the story is different, it is possible

using System.Diagnostics;

class Exemplo
{
    static void Main()
    {
        Process.Start("python", @"c:\pasta\arquivo.py");
    }
}

If python not globally installed (in environment variables), so do so:

Process.Start(@"c:\pasta_da_instalacao_do_python\python.exe", @"c:\pasta\arquivo.py");

If you want to pick up the output/response do as per

Process process = new Process();
process.StartInfo.FileName = "python";
process.StartInfo.Arguments = @"c:\pasta\arquivo.py";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true; //Pega saída de erros
process.StartInfo.RedirectStandardOutput = true; //Pega a saída        
process.Start();

StreamReader reader = process.StandardOutput;
string output = reader.ReadToEnd();

Console.WriteLine(output);

process.WaitForExit();
process.Close();

Source:

-1

You can make a system call

Process.start(@"python C:\ApertouR.py")

But I don’t know what kind of application this is.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.