PyScope missing in Python .NET - c#

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?

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.

Related

My System.CommandLine app won't build! It can't find a CommandHandler. Do I need to write it?

I am using VS 2022, .Net 6.0, and trying to build my first app using System.CommandLine.
Problem: when I build it, I get an error
The name 'CommandHandler' does not exist in the current context
The code I'm trying to build is the sample app from the GitHub site: https://github.com/dotnet/command-line-api/blob/main/docs/Your-first-app-with-System-CommandLine.md , without alteration (I think).
It looks like this:
using System;
using System.CommandLine;
using System.IO;
static int Main(string[] args)
{
// Create a root command with some options
var rootCommand = new RootCommand
{
new Option<int>(
"--int-option",
getDefaultValue: () => 42,
description: "An option whose argument is parsed as an int"),
new Option<bool>(
"--bool-option",
"An option whose argument is parsed as a bool"),
new Option<FileInfo>(
"--file-option",
"An option whose argument is parsed as a FileInfo")
};
rootCommand.Description = "My sample app";
// Note that the parameters of the handler method are matched according to the names of the options
rootCommand.Handler = CommandHandler.Create<int, bool, FileInfo>((intOption, boolOption, fileOption) =>
{
Console.WriteLine($"The value for --int-option is: {intOption}");
Console.WriteLine($"The value for --bool-option is: {boolOption}");
Console.WriteLine($"The value for --file-option is: {fileOption?.FullName ?? "null"}");
});
// Parse the incoming args and invoke the handler
return rootCommand.InvokeAsync(args).Result;
}
I have installed the latest version of System.Commandline: 2.0.0-beta2.21617.1
SURELY I am just being a big fat idiot in some respect. But I don't see it.
Any insight would be welcomed.
This issue is caused by updating the CommandLine 2.0 Beta 2 package. Add the reference System.CommandLine.NamingConventionBinder to the references to fix the problem. Follow the announcements on command-line-api's GitHub account:
In your project, add a reference to System.CommandLine.NamingConventionBinder.
In your code, change references to the System.CommandLine.Invocation namespace to
use System.CommandLine.NamingConventionBinder, where the CommandHandler.Create
methods are now found. (There’s no longer a CommandHandler type in
System.CommandLine, so after you update you’ll get compilation errors until you
reference System.CommandLine.NamingConventionBinder.)
If you want to continue with the old habits, try using older versions of the System.CommandLine package.
References
Announcing System.CommandLine 2.0 Beta 2 and the road to GA
Think you are missing a using line:
using System;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.IO;
I can't swear that's it, but it looks like CommandHandler is defined in a namespace not referenced by a using (in your current code), so System.CommandLine.Invocation may be the key!

How to access android system settings with Unity in C#

I'm making an app and need to be able to check if settings like : Bluetooth/Phone Rotation/Flashlight/Plane Mode/GPS/Phone Brightness/Silent Mode, are activated on an android phone.
I haven't found any way to do it within Unity, using C#. I found ways to do it using Xamarin but none of them work with Unity (or maybe I haven't done it right), the only way I found is using Java and making it into a plugin and call it in a C# script. But I can't find a clear way to make this work. If this is the only solution could you please explain how to do it, all the documentation I find is from old versions from 2014.
I think there is a simple solution for this but I simply can't find it. And the manifest part is not a problem, I'll add the permissions needed.
In Java the methods you want to call should be public or static, you must build your java source as a library (in build.gradle: apply plugin: 'com.android.library'), and add the .aar to Unity's Assets/Plugins/Android/ folder.
Then you can instantiate your plugin in Unity like so:
// this class string is the package at the top of your Java class extended with the class name, e.g.:
// package com.yourcompany.you.package;
string classString = "com.yourcompany.you.package.className";
// Get the class
var tempAjc = new AndroidJavaClass(classString);
// Here you can call a static method on the class that returns an instance of the class if you want to pass some parameters upon creation
_androidObject = tempAjc.CallStatic<AndroidJavaObject>("CreateInstance",
new object[] {arg1, arg2});
// non static call on your new instance
_androidObject.Call("PassingMoreStuff", initParam);
// if you want to return something from Java to Unity:
int javaVal = _androidObject.Call<int>(methodName, parameters);

Can't find Foundation.NSJavaScriptExtension class in app extension

I'm developping an app extension for iOS with Xamarin Studio. I tried to use a class that is supposed to be in the Foundation API, but I can't find it. The class is called NSJavaScriptExtension.
I tried to access it by specifying the namespace:
Foundation.NSJavaScriptExtension
I also tried to use the using directive:
using Foundation;
When I tried compiling it, I got the following error message:
Error CS0103: The name 'NSJavaScriptExtension' does not exist in the
current context (CS0103)
This is really strange because the Xamarin documentation says that it exists.
Here's my code :
// Create an extension Item
var extensionItem = new NSExtensionItem ();
// Create a Final value Dictionary
var finalize = new NSMutableDictionary ();
finalize.Add (NSJavaScriptExtension.FinalizeArgumentKey, new NSString ("{bgColor:red}")); // <- here
// Create an item provider and attach it to the extension item
var provider = new NSItemProvider (finalize, MobileCoreServices.UTType.PropertyList);
extensionItem.Attachments = new NSItemProvider[]{ provider };
// Send results to the calling Host App
ExtensionHelper.ExtensionContext.CompleteRequest (new NSExtensionItem[]{ extensionItem },
(completionHandler) => {
return;
});
The type NSJavaScriptExtension was added in XI 9.0. The easiest way to get it is to upgrade to the latest stable release, which can target older iOS versions as well.
If you cannot update then you can load any constant manually at runtime, like:
using Foundation;
using ObjCRuntime;
...
IntPtr foundation = Dlfcn.dlopen (Constants.FoundationLibrary, 0);
NSString FinalizeArgumentKey = Dlfcn.GetStringConstant (foundation.Handle, "NSExtensionJavaScriptFinalizeArgumentKey");

Pythonnet: how to use an embedded python intepreter?

I'm trying to use an embedded python interpreter from C# using pythonnet (the python3 compatible version found at https://github.com/renshawbay/pythonnet)
My interpreter is located in D:\src\scratch\TestPythonNet\TestPythonNet\PythonRuntime and has the "Lib" and "Libs" folder from the python distribution.
I've tested using the following code:
<!-- language: c# -->
PythonEngine.PythonHome = #"D:\src\scratch\TestPythonNet\TestPythonNet\PythonRuntime";
PythonEngine.ProgramName = "PythonRuntime";
PythonEngine.Initialize();
using (Py.GIL())
{
PythonEngine.RunSimpleString("print(1)");
}
But, it doesn't work. I get a "SystemError: PyEvalCodeEx: NULL globals". Everytime I try to get an object from python, the code fails.
What am I doing wrong?
I think I've found the answer. If I add a reference to the "clr" module provided by pythonnet, it does work
PythonEngine.PythonHome = #"D:\src\scratch\TestPythonNet\TestPythonNet\PythonRuntime";
PythonEngine.ProgramName = "PythonRuntime";
PythonEngine.Initialize();
// ==>
PyObject a = PythonEngine.ImportModule("clr");
using (Py.GIL())
{
PythonEngine.RunSimpleString("print(1)");
}

How to invoke C#/.NET namespace in IronPython?

I'm looking to replicate the following in IronPython and searching has so far been fruitless and/or disappointing.
namespace Groceries
{
public class ChocolateMilk : Milk
{
// Other stuff here
}
}
The idea would be that the compiled Python DLL will be loaded into a C# program through System.Reflection.Assembly.Load and a GetType("Groceries.ChocolateMilk") on the loaded DLL would not return null.
The most recent answer I was able to find was in 2008 and said that it was impossible without using the Hosting API - http://lists.ironpython.com/pipermail/users-ironpython.com/2008-October/008684.html.
Any suggestions on how to accomplish this would be greatly appreciated. Any conclusions that this is currently impossible to do via IronPython will also be appreciated, but less so.
I'm a bit confused on what you're asking here. Are you trying to instantiate that C# code in your IronPython modules? Or do you have the equivalent classes written in IronPython and you want to instantiate them in your C# code?
Based on the link you posted, I suppose you're going for the latter and have IronPython classes that you want instantiated in your C# code. The answer is, you cannot directly instantiate them. When you compile IronPython code to an assembly, you cannot use the types defined there with your regular .NET code since there is not a one-to-one mapping between IronPython classes and .NET classes. You would have to host the assembly in your C# project and instantiate it that way.
Consider this module, Groceries.py compiled to Groceries.dll residing in the working directory:
class Milk(object):
def __repr__(self):
return 'Milk()'
class ChocolateMilk(Milk):
def __repr__(self):
return 'ChocolateMilk()'
To host the module in your C# code:
using System;
using IronPython.Hosting;
using System.IO;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
var engine = Python.CreateEngine();
var groceriesPath = Path.GetFullPath(#"Groceries.dll");
var groceriesAsm = Assembly.LoadFile(groceriesPath);
engine.Runtime.LoadAssembly(groceriesAsm);
dynamic groceries = engine.ImportModule("Groceries");
dynamic milk = groceries.ChocolateMilk();
Console.WriteLine(milk.__repr__()); // "ChocolateMilk()"
}
}
Otherwise to go the other way and create an instance of your .NET type in your IronPython code (as your title suggests). You'd need to add the path to your assembly, reference it, then you could instantiate it as needed.
# add to path
import sys
sys.path.append(r'C:\path\to\assembly\dir')
# reference the assembly
import clr
clr.AddReferenceToFile(r'Groceries.dll')
from Groceries import *
chocolate = ChocolateMilk()
print(chocolate)

Categories

Resources