C#中添加对python文件或者对python包的引用时出现"no module .."的问题时的解决办法。
对hello.py 做一些简单的修改
添加
import syssys.path.append(<DIR>)
因为我的hashlib在该目录"D:IronPython2.7Lib"下,<DIR>为"D:IronPython2.7Lib
////
def load_config(keyword_category, config_path = r'./config'): #load keywords under designated category from config file ###INPUT: str keyword_category -> also serves as name of config file; _ #str config_path -> location of config files ###OUTPUT: list result -> keywords loaded from config file import os.path config_file = os.path.join(config_path, keyword_category+'.txt') f = read(config_file, 'r') result = [] for line in f: result.append(line.replace(' ','').decode('utf8')) f.close() return result
在C#这一端,调用代码如下(项目已经添加引用ironpython.dll, ironpython.hosting.dll, microsoft):
public string[] GetKeywords(string category, string config_path) { ScriptRuntime pyRunTime = Python.CreateRuntime(); dynamic pyScript = pyRunTime.UseFile(@".python scriptsfile_utils.py"); List<string> tmp = pyScript.load_config(category, config_path); tmp.TrimExcess(); string[] result = tmp.ToArray(); return result; }
运行时VS2013反馈的错误信息如下:
An unhandled exception of type 'IronPython.Runtime.Exceptions.ImportException' occurred in Microsoft.Dynamic.dll
Additional information: No module named os.path
很奇怪的一点是,其他python代码里引用os等标准库完全没有问题,不知道为什么惟独os.path会出现问题