[Python.NET] How to run a command by Embedded Python?

Seungweon Park swpark71 at gmail.com
Thu Mar 28 22:35:29 CET 2013


Hi,

I wrote a code PythonWrapper and SimplePythonTest which uses PythonWrapper.


using SimplePython;

namespace SimplePythonTest
{
    /// <summary>
    /// Python Wrapper Tests
    /// </summary>
    [TestFixture]
    public class PythonTests
    {
        PythonWrapper py;
        /// <summary>
        /// PythonTests Constructor
        /// </summary>
        public PythonTests()
        {
            py = new PythonWrapper();

            py.Init();

            PyObject po;
            po = py.LoadModule("os");
            po = py.LoadModule("sys");
            po = py.LoadModule("psutil");
        }

        /// <summary>
        /// Python Simple Test
        /// </summary>
        [Test]
        public void CommonPythonTests()
        {
            PyObject po = py.Execute("os.getcwd()");
            Trace.WriteLine(po.Repr());

            py.Close();
        }
    }
}


namespace SimplePython
{
    /// <summary>
    /// Python Wrapper via XMLRPC/Python 2.7.3/.Net for Python.
    /// </summary>
    public class PythonWrapper
    {
        /// <summary>
        /// Inter Lock
        /// </summary>
        private IntPtr gs;

        /// <summary>
        /// Constructor
        /// </summary>
        public PythonWrapper()
        {
        }

        /// <summary>
        /// Initialize PythonEngine
        /// </summary>
        public void Init()
        {
            PythonEngine.Initialize();
            gs = PythonEngine.AcquireLock();

        }

        /// <summary>
        /// Load Module
        /// </summary>
        /// <param name="strModule">Module Name</param>
        /// <returns></returns>
        public PyObject LoadModule(string strModule)
        {
            return PythonEngine.ImportModule(strModule);
        }

        /// <summary>
        /// Execute Python Command
        /// </summary>
        /// <param name="strCommand">Python Command</param>
        /// <returns></returns>
        public PyObject Execute(string strCommand)
        {
            PyObject po = PythonEngine.RunString(strCommand);

            return po;
        }

        public void Close()
        {
            PythonEngine.ReleaseLock(gs);
            PythonEngine.Shutdown();
        }
    }
}

When testing (CommonPythonTests),  it initializes and loads modules, but
PythonEngine.RunString() doesn't seem to work properly. Is any something
wrong in my code which gets os.getcwd()? Furthermore, I can't find the
difference between PythonEngine.RunString() and
PythonEngine.RunSimpleString().

Thank you,
Spark.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/pythondotnet/attachments/20130328/a6285b4b/attachment.html>


More information about the PythonDotNet mailing list