Scripting methods for invoking Python in the. Net framework (for example, VB and C #)

Source: Internet
Author: User
Tags throw exception hosting python script

A project involves a scenario in which the original project written by Vb/c# to invoke some of Python's methods to accomplish a particular operation, which involves invoking the Python scripting method in the. Net framework.

The procedure is as follows:

1): Show a simple python code, pass a parameter, and return the modified string, the file name is mytest.py

def mytestfunction (name)     return "  " + Name

2): We use third-party tools to do this, then this third-party tool is IronPython, IronPython is a python implementation on. NET and Mono, an open source project based on the Microsoft DLR engine, where you can download or trace the source code (HTTPS://GITHUB.COM/IRONLANGUAGES/IRONPYTHON2). Then we can download the installation file (https://github.com/IronLanguages/ironpython2/releases/tag/ipy-2.7.8) to this link, After the installation files are installed, we can find the DLLs we need (IronPython.dll, IronPython.Modules.dll, Microsoft.Dynamic.dll, and so on under the corresponding installation directory). Microsoft.Scripting.dll) and a folder named Lib, as shown in:

3): We use vs to create a VB project, and then refer to the above four DLLs, then we can make a specific call, assuming that our Python code files placed in the directory is D:\Code\PyTest\mytest.py If necessary, copy this file to the VB Execution directory and replace the corresponding Pythonpath

As shown in the following code:

Importsironpython.hostingImportsMicrosoft.Scripting.Hosting Public ClassForm1Private SubCallpython ()DimPythonPath ="D:\Code\PyTest\mytest.py"        DimPyruntime asScriptruntime =python.createruntime ()DimFileobj as Object=Pyruntime. Usefile (PythonPath)Dimresult = Fileobj.mytestfunction (" World")    End SubEnd Class

So we have completed the VB call Python script method through IronPython, we can continue to refer to the following connection: 41985163

The Python script method here is very simple, there is no other script reference, but the actual project of such simple code is mostly meaningless, always refer to other module to achieve more complex logic.

Now we're going to step up, how do we accomplish our goal if there's a mutual reference between Python scripts? Take a look at 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,

ImportOSclassFileoperator:defwriteinfotofile (self, path): File= Open (Path,"W") File.write ("Hello World") File.close ()defreadinfofromfile (self, path) FileInfo=""Data=Open (Path) forEach_lineinchData:fileinfo+=each_line data.close ()returnFileInfo

Why add an extra parameter to self when implementing a method?

Please see the following connection: https://stackoverflow.com/questions/23944657/ typeerror-method-takes-1-positional-argument-but-2-were-given/42016399

File read/write 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 using Python to run the Writeinfotofile method

 from Import Fileoperator def mytestreadinfo ():     = Foperator.readinfofromfile ("D:\Code\PyTest\Test.txt")    return = Fileoperator () 

6): Then we use the following VB code to make a call to the new Python script method

Importsironpython.hostingImportsMicrosoft.Scripting.Hosting Public ClassForm1Private SubCallpython ()DimPythonPath ="D:\Code\PyTest\mytest.py"        DimPyruntime asScriptruntime =python.createruntime ()DimFileobj as Object=Pyruntime. Usefile (PythonPath)Dimresult =Fileobj.mytestreadinfo ()End SubEnd Class

Will throw exception said: Such a module can not load, or can not find such a module. The Unhandled Exception: IronPython.Runtime.Exceptions.ImportException: No module named ... reason is that Python automatically loads the associated module when it runs itself, especially some system module, such as the OS, but we can't automatically create such a link when we call it externally. Because we want to explicitly indicate in the source file of Python the folder where the referenced system source files are located, so that they can find the associated source file under the specified folder.

So where are these source files? We can go to the Python installation directory to find, or we can go to our 2nd Step IronPython installation directory under the search, that is, the Lib folder, and then copy this folder to our test Python sibling folder, with a relative path specified, of course you can also do not copy, Then navigate to the Lib folder with the absolute path

The code looks like this:

Import syssys.path.append (". \lib")  from Import Fileoperator def mytestreadinfo ():     = Foperator.readinfofromfile ("D:\Code\PyTest\Test.txt")      return= Fileoperator ()

So we can use the 6th step in the VB code to call to succeed.

Note: When using relative paths, be aware of the location of the file and ensure that it is successfully located.

For more details, refer to the following connection:

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/

41985163

Scripting methods for invoking Python in the. Net framework (for example, VB and C #)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.