C#调用python

首先下载最新的IrorPython(点击打开链接),目前最新的是2.7.8。安装。

引用安装路径下的DLL(C:\Program Files\IronPython 2.7)

新建一个Winfrom程序调用写好的Python代码

ScriptEngine pyEngine = Python.CreateEngine();//创建Python解释器对象
            ScriptSource source = pyEngine.CreateScriptSourceFromFile(@"E:\TestPythonProjects\PythonApplication1\PythonApplication2\AAnalyze27.py");
            ScriptScope scope = pyEngine.CreateScope();
            try
            {
                //设置参数  
                scope.SetVariable("arg1", tbAddress.Text);
            }
            catch (Exception)
            {
                MessageBox.Show("输入有误。");
            }

            source.Execute(scope);
            //获取结果【在python中为全局变量值】
            dynamic name = scope.GetVariable("name");
            if (name != null)
            {
                tbName.Text = name;
            }

若python引用了第三方库,则需要将第三方库文件拷入到如下路径中:

在python文件头部需加入搜索引用:

如此,便可。

转载自:https://blog.csdn.net/World3000/article/details/79973586

You may also like...