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?
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 very new to this and require some help. I am trying to call something basic as per the section below using C# with the IronPython nuget.
Below is what I am trying:
Microsoft.Scripting.Hosting.ScriptEngine py = Python.CreateEngine();
Microsoft.Scripting.Hosting.ScriptScope s = py.CreateScope();
py.Execute("import numpy as np incomes = np.random.normal(27000, 15000, 10000) x = np.mean(incomes)", s);
I keep receiving the following error:
An exception of type 'Microsoft.Scripting.SyntaxErrorException' occurred in Microsoft.Scripting.dll but was not handled in user code
Any help would be appreciated thank you
Be aware of indentation when working with Python. This works:
using IronPython.Hosting;
namespace PythonFromCSharp
{
class Program
{
static void Main(string[] args)
{
Microsoft.Scripting.Hosting.ScriptEngine py = Python.CreateEngine();
Microsoft.Scripting.Hosting.ScriptScope s = py.CreateScope();
// add paths to where your libs are installed
var libs = new[] { #"c:\path\to\lib1", #"c:\path\to\lib2" };
py.SetSearchPaths(libs);
py.Execute(
#"import numpy as np
incomes = np.random.normal(27000, 15000, 10000)
x = np.mean(incomes)"
, s);
}
}
}
Your Python syntax is incorrect. Insert line breaks (\n)
py.Execute("import numpy as np\nincomes = np.random.normal(27000, 15000, 10000)\nx = np.mean(incomes)", s);
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 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 written a python webservice using saoplib
my python web service code :
import soaplib
from soaplib.core.service import rpc, DefinitionBase,soap
from soaplib.core.model.primitive import String, Integer
from soaplib.core.server import wsgi
from soaplib.core.model.clazz import Array
class HelloWorldService(DefinitionBase):
#soap(String,_returns=String)
def say_hello(self,name):
f=open("/tmp/f.txt","w+")
f.write(name)
f.close()
return name
if __name__=='__main__':
try:
from wsgiref.simple_server import make_server
soap_application = soaplib.core.Application([HelloWorldService], 'tns')
wsgi_application = wsgi.Application(soap_application)
server = make_server('46.36.119.230', 7789, wsgi_application)
server.serve_forever()
except ImportError:
print "Error: example server code requires Python >= 2.5"
I want to call it from my c# application.So how do i call it say_hello method?
First add your webservice to C# using this address
http://46.36.119.230:7789/?wsdl
Then you can call the say_hello method this way:
ServiceReference1.ApplicationClient h = new ApplicationClient();
say_hello ss = new say_hello();
ss.name = "saeed";
say_helloResponse rs = h.say_hello(ss);
MessageBox.Show(rs.say_helloResult);