Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyScope missing in Python .NET

My problem is that I'm trying to use Python.NET inside Visual Studio, I installed Python 3.5, and the python.NET package trough nuget and trough pip too.

added namespace Python.Runtime in my Form application, and the Python.Runtime.dll is there in the references too.

I tried to use a sample code from the offical site: offical site

using Python.Runtime;

// create a person object
Person person = new Person("John", "Smith");

// acquire the GIL before using the Python interpreter
using (Py.GIL())
{
// create a Python scope
using (PyScope scope = Py.CreateScope())
{
    // convert the Person object to a PyObject
    PyObject pyPerson = person.ToPython();

    // create a Python variable "person"
    scope.Set("person", pyPerson);

    // the person object may now be used in Python
    string code = "fullName = person.FirstName + ' ' + person.LastName";
    scope.Exec(code);
  }
}

The Py.GIL() part works and I already tried to import numpy package and do some basic calculations with it, it worked well.

However the PyScope is just not recognized, nor do Py.CreateScope. ("The type or namespace PyScope could not be found")

Tried to write Python.Runtime.PyScope, tried reinstalling, tried older package, used console app and winforms app too, however nothing seems to work.

Am I missing something here?

like image 387
Neil Marko Avatar asked Apr 30 '26 16:04

Neil Marko


1 Answers

I ran into this problem too. Using var instead of PyScope worked for me. As in:

    using (var scope = Py.CreateScope())

Edit & Alternative: when I visited the definition of CreateScope(), the output type was PyModule:

public static PyModule CreateScope();
public static PyModule CreateScope(string name);

Using this instead of var also works for me:

using (PyModule scope = Py.CreateScope())

If that doesn't work for you, visiting the definition of the function and using the output type listed in your version likely will.

The var isn't picky though.

like image 173
Joshua Merrell Avatar answered May 02 '26 05:05

Joshua Merrell