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");
}
Related
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.
I wrote this code in python to draw dendrogram:
import numpy as np
from scipy.cluster.hierarchy import linkage,dendrogram
import matplotlib.pyplot as plt
x = np.array([[2,3],[5,5],[4.3,6],[5.5,4.9],[4.4,5.8],[10,10],[40,40],
[2.2,5]])
plt.scatter(x[:,0],x[:,1],s=30)
lin=linkage(x,"single")
den=dendrogram(lin,truncate_mode="none")
plt.show()
It works correctly and generates the dendrogram. After that, I want to convert this code to a method in Python script and execute it over a C# project so I can use IronPython.
But there is an error in the script at this part linkage(x,"single"), truncate_mode = "none" and this line plt.show(), as shown in the following c# code:
var pySrc =
#"def Generatedendrogram():
import numpy as np
from scipy.cluster.hierarchy import linkage,dendrogram
import matplotlib.pyplot as plt
x = np.array([[2,3],[5,5],[4.3,6],[5.5,4.9],[4.4,5.8],[10,10],[40,40]])
plt.scatter(x[:,0],x[:,1],s=30)
//There is an error in the next 2 lines
dendrogram(linkage(x,"single"), truncate_mode = "none")
plt.show()";
// host python and execute script
var engine = IronPython.Hosting.Python.CreateEngine();
var scope = engine.CreateScope();
engine.Execute(pySrc, scope);
// get function and dynamically invoke
var dendro = scope.GetVariable("Generatedendrogram");
Generatedendrogram();
How can I write this script correctly?
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 have been working on a problem for a while now which I cannot seem to resolve so I need some help! The problem is that I am writing a program in C# but I require a function from a Python file I created. This in itself is no problem:
...Usual Stuff
using IronPython.Hosting;
using IronPython.Runtime;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
namespace Program
{
public partial class Form1 : Form
{
Microsoft.Scripting.Hosting.ScriptEngine py;
Microsoft.Scripting.Hosting.ScriptScope s;
public Form1()
{
InitializeComponent();
py = Python.CreateEngine(); // allow us to run ironpython programs
s = py.CreateScope(); // you need this to get the variables
}
private void doPython()
{
//Step 1:
//Creating a new script runtime
var ironPythonRuntime = Python.CreateRuntime();
//Step 2:
//Load the Iron Python file/script into the memory
//Should be resolve at runtime
dynamic loadIPython = ironPythonRuntime.;
//Step 3:
//Invoke the method and print the result
double n = loadIPython.add(100, 200);
numericUpDown1.Value = (decimal)n;
}
}
}
However, this requires for the file 'first.py' to be wherever the program is once compiled. So if I wanted to share my program I would have to send both the executable and the python files which is very inconvenient. One way I thought to resolve this is by adding the 'first.py' file to the resources and running from there... but I don't know how to do this or even if it is possible.
Naturally the above code will not work for this as .UseFile method takes string arguments not byte[]. Does anyone know how I may progress?
Lets start with the simplest thing that could possibly work, you've got some code that looks a little like the following:
// ...
py = Python.CreateEngine(); // allow us to run ironpython programs
s = py.CreateScope(); // you need this to get the variables
var ironPythonRuntime = Python.CreateRuntime();
var x = py.CreateScriptSourceFromFile("SomeCode.py");
x.Execute(s);
var myFoo = s.GetVariable("myFoo");
var n = (double)myFoo.add(100, 200);
// ...
and we'd like to replace the line var x = py.CreateScriptSourceFromFile(... with something else; If we could get the embedded resource as a string, we could use ScriptingEngine.CreateScriptSourceFromString().
Cribbing this fine answer, we can get something that looks a bit like this:
string pySrc;
var resourceName = "ConsoleApplication1.SomeCode.py";
using (var stream = System.Reflection.Assembly.GetExecutingAssembly()
.GetManifestResourceStream(resourceName))
using (var reader = new System.IO.StreamReader(stream))
{
pySrc = reader.ReadToEnd();
}
var x = py.CreateScriptSourceFromString(pySrc);
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.