[Python.NET] Using PyScope to set variables I can use in imported scripts

Luke, Steve Steve.Luke at moldev.com
Wed Sep 19 12:00:11 EDT 2018


I am new to Python.Net and trying to convert an application that used IronPython to embed a Python environment into a .Net application and allow the user to run Python scripts inside our application.  The part that embeds the Python environment is VB.Net (but could be C# if that would be better).


I am running into problems setting variables in the scope such that they can be used in the Python scripts we call.  I keep getting an error: NameError: global name 'Bridge' is not defined.


This is the VB code I am trying to use:

        PythonEngine.Initialize()

        Using (Py.GIL())
            Dim moduleName As String = "PrintToBridge"
            Dim pythonCommandLine As String = "Not used yet"

            Dim scope As PyScope = Py.CreateScope()
            Try
                scope.Set("Bridge", bridge)
                scope.Set("SetupParams", cmdLine)

                Dim script As Object = scope.Import(moduleName)
                bridge.mm.PrintMsg("Scope has Bridge:" + Str(scope.Contains("Bridge")))
                script.Startup(pythonCommandLine)
            Finally
                scope.Dispose()
            End Try
        End Using

The Python script:

def Startup(param):
    Bridge.mm.PrintMsg('Startup called')

def Docommand(param):
    Bridge.mm.PrintMsg('docommand called')

def Shutdown():
    Bridge.mm.PrintMsg('Shutdown called')



How can I set a variable such that it would be recognized by the called Python script?  Importing the script works, I can force python-y things to happen.  And the check to see if the object I want is in scope returns true.  But it still isn't available in Python.


I have tried scope.Eval(moduleName + ".Startup('" + pythonCommandLine + "')") and Exec() with locals:

                Dim locals As PyDict = New PyDict()
                locals.SetItem("Bridge".ToPython(), bridge.ToPython())
                scope.Exec(moduleName + ".Startup('" + pythonCommandLine + "')", locals)


All with the same effect.  Any ideas on how to get set variables so scripts can gain access to them?


Thanks,

Steve


Please be advised that this email may contain confidential information. If you are not the intended recipient, please notify us by email by replying to the sender and delete this message. The sender disclaims that the content of this email constitutes an offer to enter into, or the acceptance of, any agreement; provided that the foregoing does not invalidate the binding effect of any digital or other electronic reproduction of a manual signature that is included in any attachment.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/pythondotnet/attachments/20180919/30a160c7/attachment.html>


More information about the PythonDotNet mailing list