C # calls Python scripts and third party modules using Python
C Call Python script and use Python third party module to add Reference library C code embedded python load Python code from file use Python to install the third module
My homepage www.csxiaoyao.com
IronPython is a Python language that is implemented on. NET and can invoke Python code in a. NET environment using IronPython. "Add Reference Library"
After Visual Studio creates a new project, add references to IronPython.dll and Microsoft.Scripting.dll (located under the IronPython installation directory). "C # code embedded python"
The easiest way to use it is as follows:
var engine = IronPython.Hosting.Python.CreateEngine ();
Engine. Createscriptsourcefromstring ("print ' Hello world! '"). Execute ();
"Load python code from a file"
In general, we still have to write the Python code separately in the file. Create a new Python file in the project, such as hello.py, directly under the Publish path (you can also set its property copy to Output directory value of Copy if newer). Write the following code under hello.py:
#无返回值函数
def say_hello ():
print "hello!"
#有返回值函数
def get_text (): Return
"text to hello.py"
#带参函数
def add (arg1, arg2): return
arg1 + arg2
The C # code is as follows:
Run Python script
var engine = IronPython.Hosting.Python.CreateEngine ();
var scope = engine. Createscope ();
var Source = engine. Createscriptsourcefromfile ("hello.py");
Source. Execute (scope);
Call no return value function
var Say_hello = scope. Getvariable<func<object>> ("Say_hello");
Say_hello ();
Call has return value function
var get_text = scope. Getvariable<func<object>> ("Get_text");
var text = Get_text (). ToString ();
Console.WriteLine (text);
Call with the parameter function
var add = scope. Getvariable<func<object, Object, object>> ("Add");
var result = Add (1, 2);
Console.WriteLine (result);
"Third module installed with Python"
Python's own library can be invoked directly in a script, but the following error occurs in a direct call to a Third-party library (calling third party RSA):
An unhandled exception of type ' IronPython.Runtime.Exceptions.ImportException ' occurred in Microsoft.Dynamic.dll
Additional Information:no module named RSA
Show no modules found, set Sys.path, as follows:
Import sys
sys.path.append (' c:\\python27\\lib ')
sys.path.append (' c:\\python27\\lib\\site-packages\\ Setuptools-12.0.3-py2.7.egg ')
sys.path.append (' C:\\python27\\lib\\site-packages\\rsa-3.1.1-py2.7.egg ')
Import RSA