我已经使用Python.Net一个星期了,但是我找不到任何以嵌入式方式使用Python.Net的示例代码,尽管Python.Net源代码有几个嵌入测试。我已经从之前的电子邮件列表(Python.Net)中搜索了很多帖子,结果并不一致,而且毫无头绪。
我想做的是在通过Python.Net从python提示符中执行python命令'print 2+3‘之后,从C#代码中获得结果(print 2+3 po),因为IronPython与我当前使用的模块不兼容。
当我在nPython.exe中执行它时,它像我预期的那样打印出5。但是,当我从C#的嵌入式方式运行这段代码时。它总是返回'null‘。你能给我一些想法,我如何才能得到执行结果?
谢谢你,斯帕克
环境: 1. .Net 2008 R2,Windows 4.0.用Python27编译Python.Net,UCS2在VS2012 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();
}
}
}发布于 2013-04-06 02:26:19
看起来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();
}
}
}https://stackoverflow.com/questions/15749028
复制相似问题