C# 如何调用Python文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 如何调用Python文件相关的知识,希望对你有一定的参考价值。
我已经写好啦一个Python文件
import subprocess
import re
import sys
......
我用c#引用IronPython.dll
var engine = IronPython.Hosting.Python.CreateEngine();
var scope = engine.CreateScope();
//engine.SetSearchPaths(new List<string>() @"D:\Python27\Lib" );
var source = engine.CreateScriptSourceFromFile(@"my.py");
source.Execute();
执行到这里就报错:
在 Microsoft.Scripting.Runtime.LightExceptions.ThrowException(LightException lightEx)
在 Microsoft.Scripting.Runtime.LightExceptions.CheckAndThrow(Object value)
在 Microsoft.Scripting.Interpreter.FuncCallInstruction`2.Run(InterpretedFrame frame)
在 Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
在 Microsoft.Scripting.Interpreter.LightLambda.Run1[T0,TRet](T0 arg0)
在 IronPython.Compiler.RuntimeScriptCode.InvokeTarget(Scope scope)
在 IronPython.Compiler.RuntimeScriptCode.Run(Scope scope)
在 IronPython.Runtime.PythonContext.InitializeModule(String fileName, ModuleContext moduleContext, ScriptCode scriptCode, ModuleOptions options)
在 IronPython.Runtime.PythonContext.CompileModule(String fileName, String moduleName, SourceUnit sourceCode, ModuleOptions options, ScriptCode& scriptCode)
在 IronPython.Runtime.PythonContext.CompileModule(String fileName, String moduleName, SourceUnit sourceCode, ModuleOptions options)
在 IronPython.Runtime.Importer.LoadFromSourceUnit(C
1. 安装IronPython
到http://ironpython.codeplex.com/下载IronPython。
安装下载下来的安装包(要先装VS啊)。
2. 创建项目
创建一个C#的控制台应用程序。
添加引用: 浏览到IronPython的安装目录中,添加对IronPython.dll,Microsoft.Scripting.dll 两个dll的引用。
3. 添加Python文件到当前的项目中
创建一个文本文件命名为:hello.py, 编辑如下
def welcome(name):
return "hello" + name
把该文件添加的当前的项目中。
4. 在C#中调用Python方法
首先添加两个引用:它们定义了Python和ScriptRuntime两个类型。
第一句代码创建了一个Python的运行环境,第二句则使用.net4.0的语法创建了一个动态的对象, OK,下面就可以用这个dynamic类型的对象去调用刚才在定义的welcome方法了。
注意:在运行前一定要把hello.py文件设为:Copy always.
否则运行时会报找不到hello.py文件,enjoy it!
参考技术A 报错通常都是最后几句比较关键,贴到一半这怎么看错误。。。本回答被提问者采纳 参考技术B IronPython没玩过python怎么调用c#的dll
1、首选运行工具 makepy.py。
2、这样就可以查看 C# dll的 com导出的 py文件了。
Python编程makepy.py代码如下:
# -*- coding: mbcs -*-# Created by makepy.py version 0.5.00
# By python version 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)]
# From type library \'XGSharpLib.tlb\'
""""""
makepy_version = \'0.5.00\'
python_version = 0x20504f0
import win32com.client.CLSIDToClass, pythoncom, pywintypes
import win32com.client.util
from pywintypes import IID
from win32com.client import Dispatch
# The following 3 lines may need tweaking for the particular server
# Candidates are pythoncom.Missing, .Empty and .ArgNotFound
defaultNamedOptArg=pythoncom.Empty
defaultNamedNotOptArg=pythoncom.Empty
defaultUnnamedArg=pythoncom.Empty
CLSID = IID(\'B38EF2FA-4639-40BC-B97C-7908CED04FF9\')
MajorVersion = 1
MinorVersion = 0
LibraryFlags = 8
LCID = 0x0
from win32com.client import DispatchBaseClass
class IComXGSharpLib(DispatchBaseClass):
CLSID = IID(\'D1965A94-0271-4C48-8AF6-2A56E256808B\')
coclass_clsid = IID(\'2302D874-18FE-4281-B329-9517F1BC8311\')
def EncryptMd5(self, orignPwd=defaultNamedNotOptArg):
# Result is a Unicode object
return self._oleobj_.InvokeTypes(2, LCID, 1, (8, 0), ((8, 1),),orignPwd
)
def EncryptSHA1(self, orignPwd=defaultNamedNotOptArg):
# Result is a Unicode object
return self._oleobj_.InvokeTypes(1, LCID, 1, (8, 0), ((8, 1),),orignPwd
)
_prop_map_get_ =
_prop_map_put_ =
class _Object(DispatchBaseClass):
CLSID = IID(\'65074F7F-63C0-304E-AF0A-D51741CB4A8D\')
coclass_clsid = IID(\'2302D874-18FE-4281-B329-9517F1BC8311\')
def Equals(self, obj=defaultNamedNotOptArg):
return self._oleobj_.InvokeTypes(1610743809, LCID, 1, (11, 0), ((12, 1),),obj
)
def GetHashCode(self):
return self._oleobj_.InvokeTypes(1610743810, LCID, 1, (3, 0), (),)
# Result is of type _Type
def GetType(self):
ret = self._oleobj_.InvokeTypes(1610743811, LCID, 1, (13, 0), (),)
if ret is not None:
# See if this IUnknown is really an IDispatch
try:
ret = ret.QueryInterface(pythoncom.IID_IDispatch)
except pythoncom.error:
return ret
ret = Dispatch(ret, u\'GetType\', \'BCA8B44D-AAD6-3A86-8AB7-03349F4F2DA2\')
return ret
_prop_map_get_ =
"ToString": (0, 2, (8, 0), (), "ToString", None),
_prop_map_put_ =
# Default property for this class is \'ToString\'
def __call__(self):
return self._ApplyTypes_(*(0, 2, (8, 0), (), "ToString", None))
def __unicode__(self, *args):
try:
return unicode(self.__call__(*args))
except pythoncom.com_error:
return repr(self)
def __str__(self, *args):
return str(self.__unicode__(*args))
def __int__(self, *args):
return int(self.__call__(*args))
from win32com.client import CoClassBaseClass
# This CoClass is known by the name \'XGSharpLib.Security\'
class Security(CoClassBaseClass): # A CoClass
CLSID = IID(\'2302D874-18FE-4281-B329-9517F1BC8311\')
coclass_sources = [
]
coclass_interfaces = [
IComXGSharpLib,
_Object,
]
default_interface = IComXGSharpLib
IComXGSharpLib_vtables_dispatch_ = 1
IComXGSharpLib_vtables_ = [
(( u\'EncryptSHA1\' , u\'orignPwd\' , u\'pRetVal\' , ), 1, (1, (), [ (8, 1, None, None) ,
(16392, 10, None, None) , ], 1 , 1 , 4 , 0 , 28 , (3, 0, None, None) , 0 , )),
(( u\'EncryptMd5\' , u\'orignPwd\' , u\'pRetVal\' , ), 2, (2, (), [ (8, 1, None, None) ,
(16392, 10, None, None) , ], 1 , 1 , 4 , 0 , 32 , (3, 0, None, None) , 0 , )),
]
_Object_vtables_dispatch_ = 1
_Object_vtables_ = [
(( u\'ToString\' , u\'pRetVal\' , ), 0, (0, (), [ (16392, 10, None, None) , ], 1 , 2 , 4 , 0 , 28 , (3, 0, None, None) , 0 , )),
(( u\'Equals\' , u\'obj\' , u\'pRetVal\' , ), 1610743809, (1610743809, (), [ (12, 1, None, None) ,
(16395, 10, None, None) , ], 1 , 1 , 4 , 0 , 32 , (3, 0, None, None) , 0 , )),
(( u\'GetHashCode\' , u\'pRetVal\' , ), 1610743810, (1610743810, (), [ (16387, 10, None, None) , ], 1 , 1 , 4 , 0 , 36 , (3, 0, None, None) , 0 , )),
(( u\'GetType\' , u\'pRetVal\' , ), 1610743811, (1610743811, (), [ (16397, 10, None, "IID(\'BCA8B44D-AAD6-3A86-8AB7-03349F4F2DA2\')") , ], 1 , 1 , 4 , 0 , 40 , (3, 0, None, None) , 0 , )),
]
RecordMap =
CLSIDToClassMap =
\'D1965A94-0271-4C48-8AF6-2A56E256808B\' : IComXGSharpLib,
\'2302D874-18FE-4281-B329-9517F1BC8311\' : Security,
\'65074F7F-63C0-304E-AF0A-D51741CB4A8D\' : _Object,
CLSIDToPackageMap =
win32com.client.CLSIDToClass.RegisterCLSIDsFromDict( CLSIDToClassMap )
VTablesToPackageMap =
VTablesToClassMap =
\'D1965A94-0271-4C48-8AF6-2A56E256808B\' : \'IComXGSharpLib\',
\'65074F7F-63C0-304E-AF0A-D51741CB4A8D\' : \'_Object\',
NamesToIIDMap =
\'_Object\' : \'65074F7F-63C0-304E-AF0A-D51741CB4A8D\',
\'IComXGSharpLib\' : \'D1965A94-0271-4C48-8AF6-2A56E256808B\',
3、举例:Python调用C# dll中的 MD5加密方法。
参考技术A Python本身无法直接调用C# DLL(只可调用C/C++DLL),需要通过IronPython来调用。http://lovesoo.org/ironpython-diao-yong-c-dll-han-shu-fang-fa.html 参考技术B 查一下comtype的资料,用c#写com组建调用
以上是关于C# 如何调用Python文件的主要内容,如果未能解决你的问题,请参考以下文章
C#调用了一个DLL文件,如何查看DLL的使用方法?小白求问