xxxxxxxxxx
public string PatchParameter(string parameter, int serviceid)
{
var engine = Python.CreateEngine(); // Extract Python language engine from their grasp
var scope = engine.CreateScope(); // Introduce Python namespace (scope)
var d = new Dictionary<string, object>
{
{ "serviceid", serviceid},
{ "parameter", parameter}
}; // Add some sample parameters. Notice that there is no need in specifically setting the object type, interpreter will do that part for us in the script properly with high probability
scope.SetVariable("params", d); // This will be the name of the dictionary in python script, initialized with previously created .NET Dictionary
ScriptSource source = engine.CreateScriptSourceFromFile("PATH_TO_PYTHON_SCRIPT_FILE"); // Load the script
object result = source.Execute(scope);
parameter = scope.GetVariable<string>("parameter"); // To get the finally set variable 'parameter' from the python script
return parameter;
}
xxxxxxxxxx
private void run_cmd(string cmd, string args)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "my/full/path/to/python.exe";
start.Arguments = string.Format("{0} {1}", cmd, args);
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using(Process process = Process.Start(start))
{
using(StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
}
xxxxxxxxxx
"""
It is actually pretty easy. Just use NuGet to add the "UnmanagedExports" package
to your .Net project.
See https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports for details.
"""
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using RGiesecke.DllExport;
class Test
{
[DllExport("add", CallingConvention = CallingConvention.Cdecl)]
public static int TestExport(int left, int right)
{
return left + right;
}
}
"""
You can then load the dll and call the exposed methods in Python (works for 2.7)
"""
import ctypes
a = ctypes.cdll.LoadLibrary(source)
a.add(3, 5)
xxxxxxxxxx
using System;
using System.IO;
using System.Diagnostics;
namespace CallPython
{
/// <summary>
/// Used to show simple C# and Python interprocess communication
/// Author : Ozcan ILIKHAN
/// Created : 02/26/2015
/// Last Update : 04/30/2015
/// </summary>
class Program
{
static void Main(string[] args)
{
// full path of python interpreter
string python = @"C:\Continuum\Anaconda\python.exe";
// python app to call
string myPythonApp = "sum.py";
// dummy parameters to send Python script
int x = 2;
int y = 5;
// Create new process start info
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python);
// make sure we can read the output from stdout
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;
// start python app with 3 arguments
// 1st arguments is pointer to itself,
// 2nd and 3rd are actual arguments we want to send
myProcessStartInfo.Arguments = myPythonApp + " " + x + " " + y;
Process myProcess = new Process();
// assign start information to the process
myProcess.StartInfo = myProcessStartInfo;
Console.WriteLine("Calling Python script with arguments {0} and {1}", x,y);
// start the process
myProcess.Start();
// Read the standard output of the app we called.
// in order to avoid deadlock we will read output first
// and then wait for process terminate:
StreamReader myStreamReader = myProcess.StandardOutput;
string myString = myStreamReader.ReadLine();
/*if you need to read multiple lines, you might use:
string myString = myStreamReader.ReadToEnd() */
// wait exit signal from the app we called and then close it.
myProcess.WaitForExit();
myProcess.Close();
// write the output we got from python app
Console.WriteLine("Value received from script: " + myString);
}
}
}
xxxxxxxxxx
public string run_cmd(string cmd, string args)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "PATH_TO_PYTHON_EXE";
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;
}
}
}