Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Would you share your idea how to call python command from embedded Python.Net?

I've been played with Python.Net for a week, but I can't find any sample code to use Python.Net in embedded way although Python.Net source has several embeddeding tests. I've searched many threads from the previous emailing list (Python.Net), the results are not consistent and are clueless.

What I'm trying to do is to get result (PyObject po) from C# code after executing python command such as 'print 2+3' from python prompt via Python.Net because IronPython doesn't have compatibility with the module that I currently using.

When I executed it from nPython.exe, it prints out 5 as I expected. However, when I run this code from embedded way from C#. it returns 'null' always. Would you give me some thoughts how I can get the execution result?

Thank you, Spark.

Enviroments: 1. Windows 2008 R2, .Net 4.0. Compiled Python.Net with Python27, UCS2 at VS2012 2. nPython.exe works fine to run '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();
        }
    }
}
like image 791
spark Avatar asked Apr 01 '13 18:04

spark


1 Answers

It seems like PythonEngine.RunString() doesn't work. Instead, PythonEngine.RunSimpleString() works fine.

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();
        }
    }
}
like image 182
spark Avatar answered Nov 15 '22 17:11

spark