spa*_*ark 6 .net c# python python-2.7 python.net
我已经使用Python.Net一周了,但我找不到任何示例代码以嵌入方式使用Python.Net,尽管Python.Net源代码有几个嵌入式测试.我搜索了以前的电子邮件列表(Python.Net)中的许多线程,结果不一致且无能为力.
我正在尝试做的是通过Python.Net从python提示符执行python命令(例如'print 2 + 3')后从C#代码获取结果(PyObject po),因为IronPython与我目前的模块没有兼容性使用.
当我从nPython.exe执行它时,它按照我的预期输出5.但是,当我从嵌入式方式从C#运行此代码时.它总是返回'null'.你能告诉我一些如何获得执行结果的想法吗?
谢谢你,Spark.
环境:1.Windows 2008 R2,.Net 4.0.使用Python27编译Python.Net,在VS2012编译UCS2 2. nPython.exe可以正常运行'print 2 + 3'
using NUnit.Framework;
using Python.Runtime;
namespace CommonTest
{
[TestFixture]
public class PythonTests
{
public PythonTests()
{
}
[Test]
public void CommonPythonTests()
{
PythonEngine.Initialize();
IntPtr gs = PythonEngine.AcquireLock();
PyObject po = PythonEngine.RunString("print 2+3");
PythonEngine.ReleaseLock(gs);
PythonEngine.Shutdown();
}
}
}
Run Code Online (Sandbox Code Playgroud)
似乎PythonEngine.RunString()不起作用.相反,PythonEngine.RunSimpleString()工作正常.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Reflection;
using Python.Runtime;
namespace npythontest
{
public class Program
{
static void Main(string[] args)
{
string external_file = "c:\\\\temp\\\\a.py";
Console.WriteLine("Hello World!");
PythonEngine.Initialize();
IntPtr pythonLock = PythonEngine.AcquireLock();
var mod = Python.Runtime.PythonEngine.ImportModule("os.path");
var ret = mod.InvokeMethod("join", new Python.Runtime.PyString("my"), new Python.Runtime.PyString("path"));
Console.WriteLine(mod);
Console.WriteLine(ret);
PythonEngine.RunSimpleString("import os.path\n");
PythonEngine.RunSimpleString("p = os.path.join(\"other\",\"path\")\n");
PythonEngine.RunSimpleString("print p\n");
PythonEngine.RunSimpleString("print 3+2");
PythonEngine.RunSimpleString("execfile('" + external_file + "')");
PythonEngine.ReleaseLock(pythonLock);
PythonEngine.Shutdown();
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1406 次 |
| 最近记录: |