So I am having some troubles importing Pyro or Pyro4 while using IronPython as a C# ScriptEngine.
The import works fine if run directly in the ipy interpreter, but I receive the following error when ipy is initialized as a script engine from a c# script.
TypeErrorException: sequence item 0: expected bytes or byte array, str found
IronPython.Runtime.Operations.ByteOps.AppendJoin (System.Object value, Int32 index, System.Collections.Generic.List`1 byteList)
IronPython.Runtime.Bytes.join (System.Object sequence)
Microsoft.Scripting.Interpreter.FuncCallInstruction`3[IronPython.Runtime.Bytes,System.Object,IronPython.Runtime.Bytes].Run (Microsoft.Scripting.Interpreter.InterpretedFrame frame)
Microsoft.Scripting.Interpreter.Interpreter.Run (Microsoft.Scripting.Interpreter.InterpretedFrame frame)
I am passing the -X:FullFrames and -X:Frames parameters to ipy at it's initialization already, so I believe I have ruled that out. In fact, this error happens whether or not I initialize with this parameters.
Here is my code in c#:
// Set the fullframes parameter in a dict
var options = new Dictionary<string, object>();
options["Frames"] = true;
options["FullFrames"] = true;
// create the engine
var ScriptEngine = IronPython.Hosting.Python.CreateEngine(options);
// and the scope (ie, the python namespace)
var ScriptScope = ScriptEngine.CreateScope();
//set the python file to execute
string scriptPath = "Assets\\test.py";
var ScriptSource = ScriptEngine.CreateScriptSourceFromFile(scriptPath);
And, of course, in the python script, I am receiving this error upon import of Pyro.
import Pyro
This error is typically obtuse for working with IPY, and I am stumped.
Any insight at all, including any techniques to get a little more traceback would be of great help.
Thanks in advance!
The issue was I was using dlls from IPY 2.7.4 and the site-lib modules for 2.7.7.
One step further, and I discovered that 2.7.4 has issues with Pyro as described here:
http://pyro-core.narkive.com/0G88Usma/bug-typeerror-expected-pointer-got-int64
If you can see your full traceback from IPY, you can see the line in Pyro that causes the issue, and a hacky fix is to comment out the method.
Related
Im trying to import use a python script in C# by using IronPython but an error keeps coming up which I don't understand, seems like it had problems importing the module. The python file runs fine by itself and i tested a simple script that prints "hello" and it worked so I might just be importing the module wrong somehow.
An unhandled exception of type 'System.MissingMemberException' occurred in Microsoft.Dynamic.dll
Additional information: 'module' object has no attribute 'setup'
Error Image
This is the code im trying to run on my C# program
var engine = Python.CreateEngine();
ICollection<string> paths = engine.GetSearchPaths();
string modulePath = #"D:\Python\Lib";
paths.Add(modulePath);
string modulePath2 = #"D:\Python\Lib\site-packages";
paths.Add(modulePath2);
engine.SetSearchPaths(paths);
dynamic py = engine.ExecuteFile(#"broadlink.py");
This is the code in my python
import broadlink
broadlink.setup('*****', '*****', 3)
devices = broadlink.discover(timeout=5)
I am trying to use the Cake-Plist addin and received an error that dynamic is not yet implemented in the version of Roslyn that was being used. Then from advise for someone else I was told to try the -Experimental switch. When using the switch I am receiving the following error when it is trying to compile the build script.
Error: Microsoft.CodeAnalysis.Scripting.CompilationErrorException: (2,1): error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'
at Microsoft.CodeAnalysis.Scripting.Script.CompilationError(DiagnosticBag diagnostics)
at Microsoft.CodeAnalysis.Scripting.Script.GetExecutor(CancellationToken cancellationToken)
at Microsoft.CodeAnalysis.Scripting.Script.Run(Object globals)
at Microsoft.CodeAnalysis.Scripting.Script.Run(Object globals)
at Cake.Scripting.Roslyn.Nightly.DefaultRoslynNightlyScriptSession.Execute(Script script)
at Cake.Core.Scripting.ScriptRunner.Run(IScriptHost host, FilePath scriptPath, IDictionary`2 arguments)
at Cake.Commands.BuildCommand.Execute(CakeOptions options)
at Cake.CakeApplication.Run(CakeOptions options)
at Cake.Program.Main()
Does anyone know what is causing this error?
A reference needs to be added to Microsoft.CSharp.dll.
#reference "Microsoft.CSharp.dll"
https://gitter.im/cake-build/cake?at=57add5a3364ad7fc5acdb660
I had a similar issue when running it on a Mac (OSX El Capitan).
I couldn't find the Microsoft.CSharp.dll anywhere on the Mac (other than in my MS Windows installation), and didn't want to add it as a dependency into one of my projects just for the sake of getting it to build like this on a mac.
I noticed, however, that Mono.CSharp.dll was being downloaded into the ./tools/Cake folder. This serves roughly the same purpose, so I tried to reference it with
#r "Mono.CSharp.dll"
That didn't work either. But when I changed it to
#r "./tools/Cake/Mono.CSharp.dll"
It worked perfectly.
Now all I need to do is determine which platform it's running on and use the correct
#r "xxx.CSharp.dll"...
You can use reflection instead of dynamic. A little less elegant but avoids issues referencing Microsoft.CSharp.dll and Mono.CSharp.dll.
The example would be written as follows.
#addin "Cake.Plist"
Task("update-ios-version")
.Does(() =>
{
var plist = File("./src/Demo/Info.plist");
var data = DeserializePlist(plist);
var itemPropertyInfo = data.GetType().GetProperty("Item");
itemPropertyInfo.SetValue(data, gitVersion.AssemblySemVer, new[] { "CFBundleShortVersionString" });
itemPropertyInfo.SetValue(data, gitVersion.FullSemVer, new[] { "CFBundleVersion" });
SerializePlist(plist, data);
});
I use the DLLs IronPython.dll and IronPython.Wpf.dll for running Iron Python in C# code using ScriptEngine and ScriptScope
I am running Iron Python script from the WPF c# code as
public static ScriptEngine engine = Python.CreateEngine();
public static ScriptScope scope = engine.CreateScope();
ScriptSource source = engine.CreateScriptSourceFromFile(Path.Combine(currentPath, temp), Encoding.ASCII, SourceCodeKind.File);
source.Execute(scope);
The script in the Source file has several methods and could be called as
Func<object> func = scope.GetVariable("scriptMethodName");
func();
I found that even after closing the application, there is still some memory not released and found in the diagnostic tool the following item
IronPython.Runtime.CodeContext <0x2890FCC> [Static variable temp$2.$constant1]
The static variables of the IronPython runtime still hold some memory as given in https://github.com/IronLanguages/main/pull/1250. This actually causes many bigger objects to still stay in memory
Is there any fix for this ?
I tried the following, but no improvement in fixing this
I included the options dictionary to
Dictionary<string, object> options = new Dictionary<string, object>();
options["Debug"] = true;
options["LightweightScopes"] = true;
Also tried
engine.Runtime.Shutdown();
scope.Engine.Runtime.Shutdown();
This issue is causing heavy memory leak,Is there a possibility to get hold of the memory used by the mainwindow and clear it explicitly
I realize that I have to DllImport the perlembed methods
perl_parse
perl_alloc
perl_free
etc.,
But not sure how to marhsall the function arguments for using it with DLLImport especially with perl_parse method.
I also realize that a related question already exists which is almost there but still the OP has solved by created a C wrapper and then using it in C#.
He says that he was not able to DLLimport PERL_SYS_INIT3.
So my question is how to properly wrap them using only C# and use it?
Look at this; I hope it will help (it was called in early version)
I got this from here (perl)
To embed a Perl interpreter in a C# program, add a reference to the COM object "Microsoft Script Control 1.0" and write code like this:
MSScriptControl.ScriptControlClass Interpreter;
Interpreter = new MSScriptControl.ScriptControlClass();
Interpreter.Language = #"PerlScript";
string Program = #"reverse 'abcde'";
string Results = (string)Interpreter.Eval(Program);
The above is equivalent to the following Perl script, which embeds a Perl interpreter within a Perl interpreter:
use Win32::OLE;
my $Interpreter;
$Interpreter = Win32::OLE->new('ScriptControl');
$Interpreter->{Language} = 'PerlScript';
my $Program = "reverse 'abcde'";
my $Results = $Interpreter->Eval($Program);
I have a Python file with as content:
import re
import urllib
class A(object):
def __init__(self, x):
self.x = x
def getVal(self):
return self.x
def __str__(self):
return "instance of A with value '%s'" % (self.getVal())
I also have a simple C# console project with the following code:
engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromFile("test.py");
ScriptScope scope = engine.CreateScope();
ObjectOperations op = engine.Operations;
source.Execute(scope); // class object created
object klaz = scope.GetVariable("A"); // get the class object
object instance = op.Call(klaz, "blabla waarde"); // create the instance
object method = op.GetMember(instance, "getVal"); // get a method
string result = (string)op.Call(method); // call method and get result (9)
Console.WriteLine("Result: " + result); //output: 'Result: blabla waarde'
(I got this from this stackoverflow querstion and answer)
If I leave out the the import urllib statement in the Python file everything works fine. (meaning it finds the re module)
But as soon as i either add import urllib or import urllib2 I get the following exception:
ImportException was unhandled
No module named urllib
So somehow it can't find the urllib. I checked the IronPython lib folder and both urllib and urllib 2 are definitely there.
The same exception gets thrown when I import urllib in the C# code. (engine.ImportModule("urllib");)
Any ideas?
I'd like to manage the imports in the python code and not in the C# code.
(So I'd like to avoid stuff like this: engine.ImportModule("urllib");)
Edit:
Some extra info on what I'm actually going to use this for (maybe someone has an alternative):
I will have a main C# application and the python scripts will be used as extensions or plugins for the main application.
I'm using Python so that I don't need to compile any of the plugins.
I believe that 'Lib' being on sys.path from the interactive console is actually done inside ipy.exe - and when embedding you will have to add the path manually. Either the engine or the runtime has a 'SetSourcePaths' (or similar) method that will allow you to do this.
I face the same problem. Following "Tom E's" suggestion in the comments to fuzzyman's reply I could successfully resolve the issue. The issue seems to be it is not able resolve the location of the urllib.py. We need to set it.
You can check the following link for the question and answer.
The version of CPython you're importing from must match your IronPython version. Use CPython v2.5 for IronPython 2.0, or v2.6 for IronPython 2.6.
Try this:
import sys
sys.path.append(r'\c:\python26\lib') # adjust to whatever version of CPython you have installed.
import urllib