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);
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 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'm trying to play around with the end user preview of roslyn and would like to execute a simple script. What I would like to do is something like:
static void Main(string[] args)
{
// Is this even valid?
var myScript = "int x = 5; int y = 6; x + y;";
// What should I do here?
var compiledScript = Something.Compile(myScript);
var result = compiledScript.Execute(myScript);
Console.WriteLine(result);
}
Can someone point to some resources and/or tell me which nuget packages to install to make this happen. I've installed the Microsoft.CodeAnalysis, but can't figure out if it doable with just that, I feel like I'm missing something.
The scripting APIs which would allow you to do this very easily were (temporarily) removed in the latest preview. You can still compile a script, emit and load the assembly and invoke its entry point by doing something along the lines of
public static class Program
{
public static void Main(string[] args)
{
var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);
var defaultReferences = new[] { "mscorlib.dll", "System.dll", "System.Core.dll" };
var script = #"using System;
public static class Program
{
public static void Main(string[] args)
{
Console.WriteLine(""Hello {0}"", args[0]);
}
}";
// Parse the script to a SyntaxTree
var syntaxTree = CSharpSyntaxTree.ParseText(script);
// Compile the SyntaxTree to a CSharpCompilation
var compilation = CSharpCompilation.Create("Script",
new[] { syntaxTree },
defaultReferences.Select(x => new MetadataFileReference(Path.Combine(assemblyPath, x))),
new CSharpCompilationOptions(OutputKind.ConsoleApplication));
using (var outputStream = new MemoryStream())
using (var pdbStream = new MemoryStream())
{
// Emit assembly to streams.
var result = compilation.Emit(outputStream, pdbStream: pdbStream);
if (!result.Success)
{
return;
}
// Load the emitted assembly.
var assembly = Assembly.Load(outputStream.ToArray(), pdbStream.ToArray());
// Invoke the entry point.
assembly.EntryPoint.Invoke(null, new object[] { new[] { "Tomas" } });
}
}
}
It will output Hello Tomas in the console :)
It appears that in the April 2014 release, scripting has been temporarily removed:
What happened to the REPL and hosting scripting APIs?
The team is reviewing the designs of these components that you saw in
previous CTPs, before re-introducing the components again. Currently
the team is working on completing the language semantics of
interactive/script code.
Im using IronPython and i try to instantiate a color from script and return it.
I got this method and send in this string as an argument
#"
from System.Windows.Media import Color
c = Color()
c.A = 100
c.B = 200
c.R = 100
c.G = 150
c
");
_python = Python.CreateEngine();
public dynamic ExectureStatements(string expression)
{
ScriptScope scope = _python.CreateScope();
ScriptSource source = _python.CreateScriptSourceFromString(expression);
return source.Execute(scope);
}
When I run this code I get
$exception {System.InvalidOperationException: Sequence contains no matching element
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate).. etc.
I can not figure out how to get this to work, so please help me.
I won't know for sure until I see either more of your source or the full stack, but I would guess you're missing having the python engine include a reference to the necessary WPF assemblies (PresentationCore for System.Windows.Media.Color AFAICT).
Depending on whether you care about the C# caller needing a reference to the same library, you can change how it gets a reference to it, but just adding PresentationCore lets me reference the necessary assembly (without strings :) and then add it to the IronPython runtime.
The below code runs fine and prints out #646496C8
using System;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
class Program
{
private static ScriptEngine _python;
private static readonly string _script = #"
from System.Windows.Media import Color
c = Color()
c.A = 100
c.B = 200
c.R = 100
c.G = 150
c
";
public static dynamic ExectureStatements(string expression)
{
var neededAssembly = typeof(System.Windows.Media.Color).Assembly;
_python.Runtime.LoadAssembly(neededAssembly);
ScriptScope scope = _python.CreateScope();
ScriptSource source = _python.CreateScriptSourceFromString(expression);
return source.Execute(scope);
}
static void Main(string[] args)
{
_python = Python.CreateEngine();
var output = ExectureStatements(_script);
Console.WriteLine(output);
}
}