Creating a class that executes python in c# - c#

I have a python code. I need to execute the python script from my c# program. After searching a bit about this, I came to know that there is mainly two ways of executing a python script from c#.
One by using 'Process' command and
the other by using Iron Python.
My question might seem dumb, is there any other way through which I can execute a python script? To be more specific, can I create a class , lets say 'Python' in c# and a member function 'execute_script' which doesn't use any api like iron python or doesn't create a process for executing the script, so that if call 'execute_scipt(mypythonprogram.py)' , my script gets executed. Sorry if this seems dumb. If this is possible, please do help me. Thanks in advance.

You can embed python into your application. View the python documentation section Extending and Embedding > Embedding Python in Another Application.
edit: this requires C++, but it should not be too difficult to build a C++ wrapper that you can use from C# (see this MSDN article).

Can you create a C# class that calls a Python script without using Iron Python and without using any external API? No. That is not possible. You have a few other choices:
Integrate the Python runtime into your program.
Smead already described one way to do this. It will work, and it does avoid creating another process, but it will be a lot of work to get it running, and it is still technically using an API. I do not recommend this for a single Python script where you don't need to pass data back and forth, but it's good to know that option exists if your other options don't pan out.
Use the Process module.
This is probably what I would do. Process has security concerns when a malicious user can cause you to execute bogus shell commands, or if the malicious user can replace the contents of the Python script. It is quite safe when you can lock down those two things.
The speed is unlikely to be a concern. It will literally only take a few minutes to set up a C# program with a process call, so if your mentor is concerned about speed, just write it and measure the speed to see if it's actually a problem.
Consider rewriting the script in C#
C# is a very expressive language with a very strong standard library, so assuming your script is not thousands of lines long, and does not use any obscure Python libraries, this might actually not be much work. If you really must not use Process, this would be the next solution I would consider.

Related

How to implement a mini language?

Environment
Windows 8.1 64bit
Microsoft Visual Studio
C#
What I'm trying to do
To implement a mini language in C#
My job in my company is to make a software which automates evaluation of the performance of company products. The evaluation involves opening valves, flowing chemicals, fetching signals from sensors, calculating some values, etc...
The issue is when a user wants to change the procedure and parameters like how long the reaction time is, the order of opening valves, whether reaction conduit is flushed out or not, the programmer has to change the source code and build another software every time the user requires it.
So I'm trying to implement a mini language in C#. A user can organize a procedure of measurement with the easy-to-understand language. The user writes a code in a txt file, my software reads it, parse each line of code, extract commands and parameters, call corresponding method in the software.
For example, a user writes a line of code like open_valve(3), my software reads the code and call an internal method send_commands_to_ADconverter(VALVE, 3) which sends appropriate commands to a target valve via an A/D converter connected to the computer. This is my conception.
However, due to lack of my programming skill, I have no idea where to start. What technology is available? What are the keywords to achieve the goal? How can I achieve this objective? Any help would be appreciated. Thanks.
Edit 1
c# - Adding scripting functionality to .NET applications - Stack Overflow doesn't refer to accessing external devices like sensors, valves via A/D converter which is crucial for my purpose, so it is unclear this is a duplicate question of the link above.
In order to create a language you need a "parser" of some sort. You will need to define a "grammar". Parsing your "progam" via the grammar will result in a structure that you can then call methods in your code that implement each feature of your language.
You are on a big learning curve here :) lots of strange things like EBNF. You will probably see lots of references to things like Gold and ANTLR. These are hugely capable but involve things like "compiler compilers" and add a level of complexity that can be confusing and require extra steps in you build pipeline.
Here are a couple of libraries I've used that allow you to define you grammar in c#.
https://github.com/picoe/Eto.Parse
https://irony.codeplex.com/
Irony is very good (I've used it for various projects) but hasn't been maintained for a while.
Eto.Parse is more recent. It also has built in parsers that allow you to create a Grammer by parsing BNF. This is very cool
If I understand, your goal is to parse a syntax written by your user and take a decision with what he typed.
I suggest you to use regular expression to match and split the user input.
There are several scripting languages which can be run directly from C#.
As your users doesn't seem to have programming knowledge it might help to use a verbose language like VBScript.
To run VBScript you can use the Scripting Control. See this question for samples: Use Microsoft Scripting Control to evaluate 'If' expressions (via c#)
IIRC the script control must be run as a 32bit application.
Well, the easiest option would be to use what you already have - C#.
You can compile C# code on the fly, and it's very easy and cheap with the new compiler, Roslyn. Then all you need to do is define your interface so that it's easy to use for the users, and put that code in a method you can call from your code. This allows you to easily support all the various development tools for C# as well, including Visual Studio/VS Code. In the simplest form, all you need to do is make your "script" implement some base class that has all the methods you want the users to have - there's certainly better approaches, but this one is very simple, which sounds like something you're looking for.
Of course, this only makes sense if you can trust your users. Making safely sand-boxed code in C# is a lot more complicated (though certainly possible), and you'd probably be better off using some ready scripting solution.

What is the best script language for Unity3D

I am starting with game dev using Unity3d and I can see there's 3 supported languages for creating scripts: C#, unityscript and Boo...
although, coming from a web-design past I am obviously used with javascript, but after few attempts I could notice Unity3d doesn't really have full support to the script language and some elements like new Date().valueOf() and some other statements within methods such as the attribute arguments and many other won't work properly, also it seems my file can't have a wrapper method that envolves all the other methods like:
(function (scope) {
function Start() {
...
}
...
}(this));
and when using something like new Date().valueOf() which is valid in JS I get:
MissingMethodException: Method not found: 'System.DateTime.valueOf'. Boo.Lang.Runtime.DynamicDispatching.MethodDispatcherFactory.ProduceExtensionDispatcher ()
So perhaps the compiler turns that initial 'unityscript' code into Boo language? so perhaps Boo is the right 'native' choice and maybe unityscript itself isn't the best way to go when developing unity3d apps?
I was thinking on a language that has full support to all known native classes and methods which will work without problem?
Sorry for any errors mentioned above and please let me know what you think.
Unity doesn't use 'real' Javascript per se. See:
http://forum.unity3d.com/threads/1117-Javascript-Version
UnityScript is based on javascript 2.0. There are a few things missing (switch statements, etc.), but they get half the speed of C++, which is way faster than Mozilla.
Once you get used to it, developing in 'JS' for unity is very very fast and flexible...but of course, if you're going to develop native components, or interface to anything in C, you'll need to use C# (in the end, C# is not difficult to learn).
If you want to be a developer in Unity and build a career on it, learn C# and use it - don't waste your time with UnityScript. You can use C# outside of Unity for programming. If your main career is already web development (or will be), then continue using javascript because ultimately C# and UnityScript have the same functionality but C# is much more widely used for programing games and applications.
The majority of the assets on the store that I have used are C# or offer both JS and C#. Mixing between the languages creates serious dependency problems because in order to use a class in either language it has to already have been processed by the Unity script loading order. To use a Javascript defined class in C#, that script file must have been processed prior to the C# script file. If the javscript class then later needs something from the C# class, you would have to find ways around it because its simply no longer possible from the javascript file. Unity has ways to define the script order.
I thought that I would warn you about mixing C# with UnityScript because if you don't focus on one or the other, you will run into this problem. Ultimately, C# is the middle ground between ambiguous languages like VB and JavaScript, and pedantic languages like C++ (I have a C/C++ background of about 10 years).
Your title "What is the best xxx" leads to opinionated answers, but I am trying to give the best advice possible without being subjective. C# will allow you to continue, even if Unity were to go away a year from now. UnityScript/JavaScript would only allow you to move into being a web developer. A C# developer can easily move into UnityScript/JavaScript, but the reverse is much harder (not impossible, just more difficult).
You should use c#. It is popular, mature, native to .NET. c# is what big teams use. Learning c# will be useful in the future. JS in Unity3D is not real JS as already mentioned and nobody heard of Boo.
JS is the most popular language for use with Unity. But the language is implemented in Mono, and so any restrictions in that implementation are going to affect Unity scripts too.
I don't know how the Mono implementation of JS works, but judging from the error message, it uses datatypes initially defined for Boo, at least. However, that doesn't mean that JS is "turned into Boo". Both are compiled into the same bytecode, which is JIT'ed and run by the Mono runtime. So neither language is "more native" than the other.
Checkout advantages and disadvantages of using c# and Java script from here.
C# is little bit faster than JavaScript and you get extra features provided by C#. You can get peoples opinion from here.
Developing with c# has advantage of Visual Studio 2010. It provides better code completion feature than Mono develop.
In JavaScript only, variables can have an unspecified type. This only occurs if you do not assign a value while declaring the variable.
Performance is slower with dynamically typed variables, and you can run into casting problems. Iif this is a concern, use #pragma strict.

Integrate a Lua editor into C# program

I'm doing a POC (Proof of concept) for a little open source project, to integrate Lua into c# looks pretty straight forward, but for this project we want to go a little further. We want to be able to edit Lua scripts from within our C# program (WPF client but we can go for winforms if that what it takes), the IDE needs basic code completion and that we can add our C# objects and methods (The ones you will be able to reach from the Lua scripts while running) so they will be auto completed.. Are they such a API available for C#?
edit: Schollii wanted some example code that i want code completion for
while true do
Mouse:setY(TrackIR:getPitch())
end
where Mouse and TrackIR are c# objects accessible from Lua script
If you want to integrate a Lua editor with syntax highlighting C#, IMO the easiest way is to go for the Scintilla control, which is available in C# through ScintillaNET. It already contains highlighter for the Lua language, and is relatively easy to embed and use.
For interfacing Lua with C#, you can use LuaInterface and back. See this question for documentation links.
Code completion will not be an easy task if you require completion beyond the standard library, which can be described in a simple dictionary. With Lua being a dynamic language, it is not trivial to deduce the contents of a variable before actually running the code up to a given point - it is not impossible, take a look at lua-inspect which is available for SciTE and ViM and allows code inspection (but it's not perfect).
If you want to try code in a running environment - i.e. you have a Lua state running with modules loaded and variables set - you can get inspired by Advanced Readline Support patch at LuaPowerPatches and adapt it to your enviroment in C#. It supports among other:
Completion of keywords and global variable names.
Recursive and metatable-aware completion of variable names.
Context sensitive delimiter completion.
It seems you just want an embeddable editor that can have code completion and syntax highlighting, preferably WPF based. It doesn't need to explicitly support Lua.
Have a look at Avalon Edit. Here is an article about it
You will have to implement the highlighting file and completions yourself within the framework it provides - but that looks easy enough.
I am not aware of any such libs. Some tool you will likely need/find useful are Luainterface and some open-source Lua editors that provide code comppletion such as blua and Scite. Note that code completion comes in different flavors, each with pros/cons in terms of power, ease of implementation, etc. For instance if you just want to provide a list of possible words that correspond to objects in global Lua namespace then you don't need much at all; if OTOH you want code completion to work with table fields and objects and various levels of nesting, work will be much increased.

Can I execute a single C# statement as a script?

I have seen online how C# allows you to compile code on the fly and I think that is a really awesome thing. I need to use this functionality for my project. But here is the problem. I'm not trying to compile a whole function or new program dynamically. I just need to call a single statement to create or delete stuff on the fly.
Is there a way C# can compile and/or run a single code statement and allow that statement to act on variables and objects in the current program's scope?
Thanks
You could compile C# using Microsoft.CSharp.CSharpCodeProvider, but that gets really complicated if you want to do it correctly, since you need to load your code in a separate App Domain to prevent memory leaks.
I'd suggest using IronPython or some other DLR language: http://www.codeplex.com/wikipage?ProjectName=IronPython
Some sample here, not sure how up-to-date it is but the idea's pretty much the same: http://www.voidspace.org.uk/ironpython/dlr_hosting.shtml
To give you an alternative rather than using C# as a scripting language, have a look at Conscript [1].
Conscript is a compiled scripting language for .NET.
[1]: http://www.codeproject.com/KB/cs/Conscript.aspx
"I just need to call a single statement to create or delete stuff on the fly." Statements like these make me shudder down to my bones. What are you trying to accomplish here, really? You want to have your user write C# statements and have your program execute them within its AppDomain? Not only is this an immense security risk, it is also a terrible user experience.
Furthermore, C# is not a scripting language. If you try to shoehorn it into being one, You're Gonna Have A Bad Time (TM).
You can, while using the debugger. At a breakpoint, just type some code into the Immediate Window in VS, and viola.
One of the best debugging features there are!
Scripting static languages comes trade-offs. There are scope and security concerns to consider, but they can be controlled.
If you're looking to execute static code (i.e. C#) from within a managed run time, I'd recommend starting with Mono. The Mono team has made strides creating a safe environment to compile JIT code into native code at run time.
Start with their official post on the subject.
It depends on what you are trying to do ... if you are looking to use it as an embedded scripting language within another application, then my answer doesn't apply, but if you just want to execute random C# statements (or programs if you like) and save them as scripts, LinqPad is awesome for that.

How can I embed a Perl interpreter in my C# program using Mono on Linux?

Does anyone know if it's possible to call a Perl sub from Mono in C#? This is on a Linux machine.
Maybe DllImport? We want to avoid loading perl every time if possible, as well.
Interop works fine with Mono under Linux to call C-Code.
Thus I would consider that you look at perlembed.
Instead of a C-program you need to create a shared C-library.
For Interop there are several good guides - a potential pitfall are sizes of datatypes, because you get really plaform/CPU dependent.
Let me know if you need anywhere more detailed information.
This thread on PerlMonks might help.

Categories