A project involves such a scenario: The original project written in VB/C# needs to call some methods of Python to complete special operations, then this involves how to call the script method of Python in .Net Framework.
The specific steps are as follows:
1): Show a simple Python code that passes a parameter and returns the modified string, the file name is mytest.py
def MyTestFunction(name) return "testing " + name
2): We use a third-party tool to achieve this operation, then this third-party tool is IronPython. IronPython is a Python implementation on .Net and Mono. It is an open source project based on Microsoft's DLR engine. You can go here Download or follow the source code (https://github.com/IronLanguages/ironpython2). Then we can download the installation file from this link (https://github.com/IronLanguages/ironpython2/releases/tag/ipy-2.7.8). After the installation file is installed, we can go to the corresponding installation directory to find our The required dlls (IronPython.dll, IronPython.Modules.dll, Microsoft.Dynamic.dll, Microsoft.Scripting.dll) and a folder named Lib as shown below:
3): We use VS to create a VB project, and then refer to the above four dlls, and then we can make specific calls, assuming that the directory where our Python code files are placed is D:\Code\PyTest\mytest .py If necessary, please copy this file to the VB execution directory, and then replace the corresponding pythonPath
As shown in the following code:
Imports IronPython.Hosting Imports Microsoft.Scripting.Hosting Public Class Form1 Private Sub CallPython() Dim pythonPath = "D:\Code\PyTest\mytest.py" Dim pyruntime as ScriptRuntime = Python.CreateRuntime() Dim fileObj As Object = pyruntime.UseFile(pythonPath) Dim result = fileObj.MyTestFunction("World") End Sub End Class
In this way, we have completed the VB call Python script method through IronPython. We can continue to refer to the following link: https://blog.csdn.net/letunihao/article/details/41985163
The Python scripting method here is very pure and flawless, without any reference to other scripts, but such simple code in actual projects is mostly meaningless, and other modules are always referenced to implement more complex logic.
Next, we are going to advance. If there are mutual references between Python scripts, how to accomplish our goal? Please see the steps below
4): Create another Python file in the same directory to read and write the file, the file name is mytest_common.py,
import them class FileOperator: def WriteInfoToFile(self, path): file = open(path, "w") file.write("Hello World") file.close() def ReadInfoFromFile(self, path) fileInfo = "" data = open(path) for each_line in data: fileInfo += each_line data.close() return fileInfo
Why add an extra parameter self when implementing a method?
Please see the following link: https://stackoverflow.com/questions/23944657/typeerror-method-takes-1-positional-argument-but-2-were-given/42016399
For file reading and writing, please refer to (http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python)
5): Then we make the following modifications to the mytest.py file, assuming that we have already generated a Test.txt file by running the WriteInfoToFile method through Python
from mytest_common import FileOperator def MyTestReadInfo(): fInfo = fOperator.ReadInfoFromFile("D:\Code\PyTest\Test.txt") return fInfo fOperator = FileOperator()
6): Then we use the following VB code to call the new Python script method
Imports IronPython.Hosting Imports Microsoft.Scripting.Hosting Public Class Form1 Private Sub CallPython() Dim pythonPath = "D:\Code\PyTest\mytest.py" Dim pyruntime as ScriptRuntime = Python.CreateRuntime() Dim fileObj As Object = pyruntime.UseFile(pythonPath) Dim result = fileObj.MyTestReadInfo() End Sub End Class
It will throw exception saying: XX module cannot be loaded, or XX module cannot be found. Unhandled Exception: IronPython.Runtime.Exceptions.ImportException: No module named ...
The reason is: when Python runs itself, it will automatically load the corresponding module, especially some system modules, such as the os in this, but we cannot automatically establish such a link when calling externally, because we need to create a link in Python. The source file clearly indicates the folder where the referenced system source files are located, so that it can search for the associated source file under the specified folder.
So where are these source files? We can look in the Python installation directory, or we can look in the IronPython installation directory in step 2, that is, the Lib folder, and then copy this folder to the same level folder of our test Python and specify it with a relative path , of course, you can also use the absolute path to locate the Lib folder without copying
The code looks like this:
import sys sys.path.append(".\Lib") from mytest_common import FileOperator def MyTestReadInfo(): fInfo = fOperator.ReadInfoFromFile("D:\Code\PyTest\Test.txt") return fInfo fOperator = FileOperator()
In this way, we can use the VB code in step 6 to call it and succeed.
Note: When using a relative path, please pay attention to the location of the file to ensure that it can be successfully located.
For more details, please refer to the following links:
https://stackoverflow.com/questions/6195781/ironpython-exe-compiled-using-pyc-py-cannot-import-module-os
https://thesesergio.wordpress.com/2013/09/11/how-to-generate-and-use-a-exe-that-uses-net-dlls-with-ironpython-pyc-py/
https://blog.csdn.net/letunihao/article/details/41985163