How to use Python in .NET-Core application? I need this for the purposes of Hackathon so the solution don't have to be 'elegant'. I've read that it's impassible to run Python scripts directly because there exists only library IronPython for standard ASP.NET but no for .NET-Core. So what is the simplest way to use Python scripts? (Because it's hackathon it's ok to use even PHP server or selenium etc. only to execute script)
2 Answers
Try this
public class RunCmd
{
public string Run(string cmd, string args)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "python";
start.Arguments = string.Format("\"{0}\" \"{1}\"", cmd, args);
start.UseShellExecute = false;// Do not use OS shell
start.CreateNoWindow = true; // We don't need new window
start.RedirectStandardOutput = true;// Any output, generated by application will be redirected back
start.RedirectStandardError = true; // Any error in standard output will be redirected back (for example exceptions)
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string stderr = process.StandardError.ReadToEnd(); // Here are the exceptions from our Python script
string result = reader.ReadToEnd(); // Here is the result of StdOut(for example: print "test")
return result;
}
}
}
}
Then
var res = new RunCmd().Run("your_python_file.py","params");
Console.WriteLine(res);
1 Comment
Lushang
This does not work for
.Net Core 3.1 + Python 3.8. use a batch script file(.bat) for Windows or shell script file (.sh) for Linux to replace the cmd.exe or bash. You may add C:\YOUR_PYTHON_PATH\python.exe %* in .bat or add /usr/bin/python3 "$@" in .shSince this shows up as one of the first entries in Google, one should probably also mention that IronPython fully supports .NetCore now, and it can easily be installed using NuGet.
This approach is simpler, since it's fewer lines of code and one less runtime to install and manage. Plus, there are a number of benefits to keeping the execution in-process (performance, debugging, type safety, etc.).
- Using NuGet, add the latest "IronPython" and "IronPython.StdLib". Alternatively, add the following to the project file:
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<PackageReference Include="IronPython" Version="2.7.10" />
<PackageReference Include="IronPython.StdLib" Version="2.7.10" />
</ItemGroup>
...
- Create a function or class to make running scripts a bit more convenient:
public class PythonScript
{
private ScriptEngine _engine;
public PythonScript()
{
_engine = Python.CreateEngine();
}
public TResult RunFromString<TResult>(string code, string variableName)
{
// for easier debugging write it out to a file and call: _engine.CreateScriptSourceFromFile(filePath);
ScriptSource source = _engine.CreateScriptSourceFromString(code, SourceCodeKind.Statements);
CompiledCode cc = source.Compile();
ScriptScope scope = _engine.CreateScope();
cc.Execute(scope);
return scope.GetVariable<TResult>(variableName);
}
}
- Run your scripts:
var py = new PythonScript();
var result = py.RunFromString<int>("d = 8", "d");
Console.WriteLine(result);
Processand call python.exe with the script-path. I don't know any other way...