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.
Related
How to run .py files and call function by using python.Net library.
i have tried below code but it is not running.
using (Py.GIL()){
var fromFile = PythonEngine.Compile(null, #"C:\PycharmProjects\pythonenet\main.py", RunFlagType.File);
fromFile.InvokeMethod("replace");//
}
main.py file:
import re
def replace():
print(re.sub(r"\s","*","Python is a programming langauge"))
When i try to run from string it is working.
using (Py.GIL()){
string co = #"def someMethod():
print('This is from static script')";
var fromString = PythonEngine.ModuleFromString("someName", co);
fromString.InvokeMethod("someMethod");
}
Finally i ended up with the following solution.
using (Py.GIL()){
dynamic os = Py.Import("os");
dynamic sys = Py.Import("sys");
sys.path.append(os.path.dirname(os.path.expanduser(filePath)));
var fromFile = Py.Import(Path.GetFileNameWithoutExtension(filePath));
fromFile.InvokeMethod("replace");
}
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.
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.
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
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.