c#


Can you execute Python code in C#? [duplicate]


Is there a way to call Python code, using IronPython I assume, from C#? If so, how?
The process is simple, especially in a C#/.NET 4 application where support for dynamic languages have been improved via usage of the dynamic type. But it all ultimately depends on how you intend to use the (Iron)Python code within your application. You could always run ipy.exe as a separate process and pass your source files in so they may be executed. But you probably wanted to host them in your C# application. That leaves you with many options.
Add a reference to the IronPython.dll and Microsoft.Scripting.dll assemblies. You'll usually find them both in your root IronPython installation directory.
Add using IronPython.Hosting; to the top of your source and create an instance of the IronPython scripting engine using Python.CreateEngine().
You have a couple of options from here but basically you'd create a ScriptScope or ScriptSource and store it as a dynamic variable. This allows you to execute it or manipulate the scopes from C# if you choose to do so.
Option 1:
Using CreateScope() to create an empty ScriptScope to use directly in C# code but usable in Python sources. You can think of these as your global variables within an instance of the interpreter.
dynamic scope = engine.CreateScope();
scope.Add = new Func<int, int, int>((x, y) => x + y);
Console.WriteLine(scope.Add(2, 3)); // prints 5
Option 2:
Using Execute() to execute any IronPython code in a string. You can use the overload where you may pass in a ScriptScope to store or use variables defined in the code.
var theScript = #"def PrintMessage():
print 'This is a message!'
PrintMessage()
";
// execute the script
engine.Execute(theScript);
// execute and store variables in scope
engine.Execute(#"print Add(2, 3)", scope);
// uses the `Add()` function as defined earlier in the scope
Option 3:
Using ExecuteFile() to execute an IronPython source file. You can use the overload where you may pass in a ScriptScope to store or use variables defined in the code.
// execute the script
engine.ExecuteFile(#"C:\path\to\script.py");
// execute and store variables in scope
engine.ExecuteFile(#"C:\path\to\script.py", scope);
// variables and functions defined in the scrip are added to the scope
scope.SomeFunction();
Option 4:
Using GetBuiltinModule() or the ImportModule() extension method to create a scope containing the variables defined in said module. Modules imported this way must be set in the search paths.
dynamic builtin = engine.GetBuiltinModule();
// you can store variables if you want
dynamic list = builtin.list;
dynamic itertools = engine.ImportModule("itertools");
var numbers = new[] { 1, 1, 2, 3, 6, 2, 2 };
Console.WriteLine(builtin.str(list(itertools.chain(numbers, "foobar"))));
// prints `[1, 1, 2, 3, 6, 2, 2, 'f', 'o', 'o', 'b', 'a', 'r']`
// to add to the search paths
var searchPaths = engine.GetSearchPaths();
searchPaths.Add(#"C:\path\to\modules");
engine.SetSearchPaths(searchPaths);
// import the module
dynamic myModule = engine.ImportModule("mymodule");
You can do quite a lot hosting Python code in your .NET projects. C# helps bridging that gap easier to deal with. Combining all the options mentioned here, you can do just about anything you want. There's of course more you can do with the classes found in the IronPython.Hosting namespace, but this should be more than enough to get you started.

Related Links

Null Conditional operator inside SelectMany - still getting NullReferenceException
Find files with Android Device Monitor from Visual Studio Emulator for Android
WPF LostFocus of UserControl not fired
Autofixtures “With”-Customizations for are ignored when using Build<T>
Why is The C# code not returning a value from Stored Procedure
Problems firing my event for dynamically link buttons in asp
Is null Property in LInq?
C# protected readonly autoproperty with only a get accessor vs protected readonly field
c# Crystal report .NET object as Data source
How to insert numbers from line into array in Collection
Don't show read only dialog when opening a word document
Does PLINQ really not preserve order?
How do I correlate a Linq query extension method to its signature in the documentation?
Datagridview event not firing
How do I redistribute Microsoft.AnalysisServices.SPClient.Interfaces
Get Standard Touchpad Swipe

Categories

HOME
oop
algolia
ftp
sip
wifi
mysqli
dronekit
window.open
blob
nltk
hiveql
msbi
browser-cache
cdn
wavefront
normals
jcodemodel
ndepend
tracking
cakephp-2.0
jinja2
nsoperation
facebook-marketing-api
versioning
reportlab
bug-reporting
ajaxcontroltoolkit
angular2-pipe
smali
grunt-contrib-uglify
dynamic-memory-allocation
folder
opencsv
eclipse-jdt
flickr
traitsui
pymunk
aweber
scip
rtsp
nscollectionview
usernotifications
delphi-xe
cakephp-3.2
ocpjp
rivets.js
hdpi
jsfl
ionic2-select
history
flask-socketio
cloudconvert
standard-error
visio-2010
dynatable
spring-cloud-aws
cardview
scanf
optional-parameters
android-tabs
racket-student-languages
class-design
key-value-store
falcon
sbt-proguard
abstract
wizard
ooad
computability
windows-kernel
database-project
lytro
updating
bootstrap-tabs
callfire
clearquest
opennebula
cl.exe
dockerpy
douglas-peucker
chunks
touch-typing
fiware-health
amzi-prolog
infor-eam
kernel-density
php-amqplib
adabas
8-puzzle
mencoder
extensibility
usersettings
dd4t
servicemanager
gssapi
event-propagation
google-email-audit-api
animationdrawable
http-response-codes
iphone-maps
qprocess
newspeak
carbon-emacs
hp-trim
datadude
zend-acl
projectgen

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App