IronPython - Load script from string in C# 4.0 application - c#

I have the following code (just a test):
var engine = Python.CreateEngine();
var runtime = engine.Runtime;
try
{
dynamic test = runtime.UseFile(#"d:\test.py");
test.SetVariable("y", 4);
test.SetVariable("client", UISession.ControllerClient);
test.Simple();
}
catch (Exception ex)
{
var eo = engine.GetService<ExceptionOperations>();
Console.WriteLine(eo.FormatException(ex));
}
But I would like to load the script from a string instead.

You can use engine.CreateScriptSourceFromString to load the script into the scope from a string, rather than a file.
StringBuilder sb = new StringBuilder();
sb.Append("def helloworld():\r\n");
sb.Append(" print \"hello world\"\r\n");
string code = sb.ToString();
ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromString(code, SourceCodeKind.File);
ScriptScope scope = engine.CreateScope();
source.Execute(scope);
Func<object> func = scope.GetVariable<Func<object>>("helloworld");
Console.WriteLine(func());

Might this example at the IronPython Cookbook help? It is on how to call your python class methods from c#...but it contains a working example of loading a script from a file as well. The example works on IronPython 2.6 (you have to be careful which version as they have been changing the Hosting around quite a bit).
http://www.ironpython.info/index.php/Using_Python_Classes_from_.NET/CSharp_IP_2.6

Related

Calling 3rd Party Module python functions from ironpython in C#

I have to call textfsm python module functions from c#.
I am using Ironpython for this.
Current code
ScriptEngine engine = Python.CreateEngine();
var paths = engine.GetSearchPaths();
string dir2 = #"C:\Program Files\Python37\Lib\site-packages";
paths.Add(dir2); // change this path according to your IronPython installation
engine.SetSearchPaths(paths);
var scope = engine.CreateScope();
var eng = engine.ExecuteFile(#"C:\Program Files\Python37\Lib\site-package\textfsm.py", scope);
I am not getting how to execute the textfsm code after this.How to pass a template and get the output.

How do I import a third-party IronPython module in .NET?

I am C# developer and I have to use an IronPython library in the .NET framework. I tested every class in Python and it's working but I am not sure how to call the library in a C# class.
When I try to call the library, I am getting a 'LightException' object has no attribute client error.
I have added lib, -x:Full frame and also all modules in the lib folder.
Here is the C# code I am using to call the Python library:
Console.WriteLine("Press enter to execute the python script!");
Console.ReadLine();
var options = new Dictionary<string, object>();
options["Frames"] = true;
options["FullFrames"] = true;
//var py = Python.CreateEngine(options);
//py.SetSearchPaths(paths);
ScriptEngine engine = Python.CreateEngine(options);
ICollection<string> paths = engine.GetSearchPaths();
string dir = #"C:\Python27\Lib\";
paths.Add(dir);
string dir2 = #"C:\Python27\Lib\site-packages\";
paths.Add(dir2);
engine.SetSearchPaths(paths);
ScriptSource source = engine.CreateScriptSourceFromFile(#"C:\Users\nikunjmange\Source\Workspaces\Visage Payroll\VisagePayrollSystem\VisagePayrollSystem\synapsepayLib\synapse_pay-python-master\synapse_pay\resources\user.py");
ScriptScope scope = engine.CreateScope();
source.Execute(scope);
dynamic Calculator = scope.GetVariable("User");
dynamic calc = Calculator();
string inputCreate = "nik12#gmail.com";
string result = calc.create(inputCreate);
The error is misleading because of a bug in IronPython 2.7.5. It should be an ImportError.
Don't add the normal CPython stdlib; it's not compatible with IronPython. Use IronPython's stdlib instead.
If you have an import of import a.b as c that's probably the culprit; either a or b does not exist but IronPython mucks up the error reporting.

Pyparsing use in C# code

I'm trying to execute python script which use pyparsing in C# with a help of IronPython. But when I try to run the script I get the ImportException that there is No module named pyparsing. I tried to add a path to a dir consisting pyparsing, but I still didn't managed how to run it proper way.
Here's the C# code:
string ExecutePythonScript(string path, string text)
{
ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
string dir = System.IO.Path.GetDirectoryName("pyparsing-1.5.7");
ICollection<string> paths = engine.GetSearchPaths();
if (!String.IsNullOrEmpty(dir))
{
paths.Add(dir);
}
else
{
paths.Add(Environment.CurrentDirectory);
}
engine.SetSearchPaths(paths);
scope.SetVariable("text", text);
engine.ExecuteFile(path, scope);
return scope.GetVariable("result");
}
Of course in the beggining of the python script I import pyparsing.
Thanks to my friend I found what was wrong.
Unpacked pyparsing package had to be placed in the Debug folder of C# app in a folder named Lib. (I suppose it also could be in folder with another name, but this was faster for me.)
Thanks to this page I also realized that I need to add some lines of code into the C# app.
So now it's:
string ExecutePythonScript(string path, string text)
{
ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
ICollection<string> Paths = engine.GetSearchPaths();
Paths.Add(".");
Paths.Add("D:\\DevTools\\IronPython 2.7\\Lib");
Paths.Add("D:\\DevTools\\IronPython 2.7\\DLLs");
Paths.Add("D:\\DevTools\\IronPython 2.7");
Paths.Add("D:\\DevTools\\IronPython 2.7\\lib\\site-packages");
engine.SetSearchPaths(Paths);
scope.SetVariable("text", text);
engine.ExecuteFile(path, scope);
(...)
And it's at least not creating that Exception.

Embedding IronPython in C#

I am just looking into using IronPython with C# and cannot seem to find any great documentation for what I need. Basically I am trying to call methods from a .py file into a C# program.
I have the following which opens the module:
var ipy = Python.CreateRuntime();
var test = ipy.UseFile("C:\\Users\\ktrg317\\Desktop\\Test.py");
But, I am unsure from here how to get access to the method inside there. The example I have seen uses the dynamic keyword, however, at work I am only on C# 3.0.
Thanks.
See embedding on the Voidspace site.
An example there, The IronPython Calculator and the Evaluator
works over a simple python expression evaluator called from a C# program.
public string calculate(string input)
{
try
{
ScriptSource source =
engine.CreateScriptSourceFromString(input,
SourceCodeKind.Expression);
object result = source.Execute(scope);
return result.ToString();
}
catch (Exception ex)
{
return "Error";
}
}
You can try use the following code,
ScriptSource script;
script = eng.CreateScriptSourceFromFile(path);
CompiledCode code = script.Compile();
ScriptScope scope = engine.CreateScope();
code.Execute(scope);
It's from this article.
Or, if you prefer to invoke a method you can use something like this,
using (IronPython.Hosting.PythonEngine engine = new IronPython.Hosting.PythonEngine())
{
engine.Execute(#"
def foo(a, b):
return a+b*2");
// (1) Retrieve the function
IronPython.Runtime.Calls.ICallable foo = (IronPython.Runtime.Calls.ICallable)engine.Evaluate("foo");
// (2) Apply function
object result = foo.Call(3, 25);
}
This example is from here.

IronPython and C# - Script Access to C# Objects

Consider the code below:
ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(null);
ScriptRuntime runtime = new ScriptRuntime(setup);
ScriptEngine engine = Python.GetEngine(runtime);
ScriptScope scope = engine.CreateScope();
scope.SetVariable("message", "Hello, world!");
string script = #"print message";
ScriptSource source = scope.Engine.CreateScriptSourceFromString(script, SourceCodeKind.Statements);
source.Execute();
This code yields the following exception:
Microsoft.Scripting.Runtime.UnboundNameException
was unhandled Message="name
'message' is not defined"
What am I missing?
It should be "source.Execute(scope);" instead of "source.Execute();"
Found this: A 3 minute guide to embedding IronPython in a C# application.

Categories

Resources