Calling C# code within Python3.6 - c#

with absolutely no knowledge of coding in C#, I wish to call a C# function within my python code. I know there's quite a lot of Q&As around the same problem, but for some strange reason, i'm unable to import a simple c# class library from a sample python module.
Here's below as to what i've done -
C# Class Library setup
I'm using the VS 2017 CE.
I create a new project TestClassLibrary under the type of ClassLibrary(.NET Standard)
The classes inside the project are as follows -
MyClass.cs
using System;
namespace TestClassLibrary
{
public class MyClass
{
public string function()
{
return "Hello World!";
}
}
}
This was built successfully, generating the .dll file under the \bin\Debug\netstandard2.0 dir as TestClassLibrary.dll
Now, I switch over to python3.6 (running on a virtualenv, backed with pythonnet 2.3.0)
main.py
import sys
sys.path.append(r"<Ablsloute Path to \bin>\Debug\netstandard2.0")
import clr
clr.AddReference(r"TestClassLibrary")
from TestClassLibrary import MyClass
When i Run python main.py, the code fails with the error -
Traceback (most recent call last):
File "main.py", line 6, in <module>
from TestClassLibrary import MyClass
ModuleNotFoundError: No module named 'TestClassLibrary'
Should the code be -
import sys
sys.path.append(r"C:\Users\DELL\source\repos\TestClassLibrary\TestClassLibrary\bin\Debug\netstandard2.0")
import clr
clr.AddReference("TestClassLibrary.dll")
from TestClassLibrary import MyClass
I get -
clr.AddReference("TestClassLibrary.dll")
System.IO.FileNotFoundException: Unable to find assembly 'TestClassLibrary.dll'.
at Python.Runtime.CLRModule.AddReference(String name)
But when i ran the code below, the code runs as expected -
import clr
clr.AddReference(r"System.Windows.Forms")
from System.Windows.Forms import MessageBox
MessageBox.Show("Hello World!")
I've no idea of what i might be missing :(

This is really janky but how I like to do things that are personal projects.
Python lets you send stuff to the command line really easily. C# can be run from command line. You probably see where I'm going with this.
Try adding C sharp to PATH. import os to python. then use this line of code when you want to run the C# script:
os.system("csc nameofscript.cs")
perhaps I've misunderstood, but this is how I would make it work on my machine

Related

ModuleNotFoundError when importing a .NET custom class in pythonnet

I'm trying to import a VERY SIMPLE custom C# class into Python using pythonnet. I've never used C# or VS, so It's probably some stupid mistake I'm doing.
I have got a solid C# code base (not written by me) that I want to drive using Python.
I have this C# class:
using System;
public class MyClass
{
string text;
public MyClass(string text)
{
this.text = text;
}
public void Write()
{
Console.WriteLine(text);
}
}
In VS 2017, I've created a .NET Core Class Library project. It compiles fine and creates a MyClass.dll file.
Then I'm trying to import it in Python:
import sys
sys.path.append(r"C:\Users\myuser\source\repos\hello\MyClass\bin\Debug\netcoreapp2.1")
import clr
clr.FindAssembly(r"MyClass")
clr.AddReference('MyClass')
import MyClass
But I always get a "ModuleNotFoundError: No module named 'MyClass'" error.
Turns out I was compiling the DLL with .NET Core. Changing to .NET Framekwork 4.5 solved the problem.
I wish the error messages were more helpful.

Importing numpy using IronPython in C#

I am trying to use numpy module functions in my Python code that i run inside my c# application in VS13.
I'm doing this to import the module:
ScriptEngine pyEngine = IronPython.Hosting.Python.CreateEngine();
ScriptScope pyScope = pyEngine.CreateScope();
pyEngine.Execute("import numpy", pyScope);
however it says "No module named numpy".
I was looking for the solution and found this:
How to install numpy and scipy for Ironpython27? Old method doens't work
Using Nilsters answer I managed to install numpy and im able to use it when i run ipy from cmd. However i dont know how to use it in my c# app in VS.
I've been looking through the files and found
\IronPython 2.7\DLLs\NumpyDotNet.dll
and also:
\IronPython 2.7\Lib\site-packages\numpy\
How do i make it possible for my python code to import numpy?

Import scikit in C# application

I am trying to import scikit-learn in a C# (console) application. I am using Python Tools for Visual Studio and IronPython 2.7.3.
I managed to run an external python script and I also managed to import numpy by declaring the python path: "C:\Python27\Lib\site-packages\"
However, when it comes to scikit-learn I get an error message:
Oops! We couldn't execute the script because of an exception: No module named _c
heck_build
___________________________________________________________________________
Contents of C:\Python27\Lib\site-packages\sklearn\__check_build:
setup.py setup.pyc setup.pyo
_check_build.pyd __init__.py __init__.pyc
__init__.pyo
___________________________________________________________________________
It seems that scikit-learn has not been built correctly.
If you have installed scikit-learn from source, please do not forget
to build the package before using it: run `python setup.py install` or
`make` in the source directory.
If you have used an installer, please check that it is suited for your
Python version, your operating system and your platform.
The file "_check_build.pyd" exists in "C:\Python27\Lib\site-packages\sklearn__check_build\".
My code is based on this article: http://devleader.ca/2013/09/23/visual-studio-c-python-sweet/
The file I am using has only the following code:
from sklearn.svm import SVC
print('Hello Python in C#')
Is it possible to add and use scikit in C#? If yes, could you please provide a workaround?
Looks like scikit-learn requires a C extension, which means it won't run under IronPython.

Import Python Module through C# .NET using IronPython

I am trying to run a Python class through C# .NET using IronPython, a couple of the Modules imported by the Python class are:
import collections
import nltk.classify.util
In order to import these when running IronPython, I am using the GetSearchPath collection of the ScriptEngine to add the path to the location of the Python library, as such:
ICollection<string> paths = pyEngine.GetSearchPaths();
string dir = #"C:\Python27\Lib\";
paths.Add(dir);
string dir2 = #"C:\Python27\Lib\site-packages\nltk\classify\";
paths.Add(dir2);
pyEngine.SetSearchPaths(paths);
This seems to run fine for the collections Module, but not the nltk.classify.util, and I get the following error when calling the Execute method of the ScriptEngine:
No module named nltk.classify.util
Even tho the util module lives in the path specified above. I take it the issue has to do with the way the import is specified in the Python class ('.' delimited), just not sure how to solve it. Any ideas where am going wrong?
Python uses the structure of a package name to search for a module, so if you ask for nltk.classify.util it will look for nltk\classify\util.py starting from each directory in the search path.
So in your example, you want to change dir2 as follows:
string dir2 = #"C:\Python27\Lib\site-packages";

how can i access C# dll from VBScript on client machine

i have created a C# dll file on my machine as shown below:
namespace myDLL
{
public class myClass
{
public string myFunction()
{
return "I am Here";
}
}
}
then i created a tlb file with "tlbexp" command,
then i used the "regasm" command n registered this dll on my machine.
When i created an object of type myClass on my machine using VBScript, everything is working fine... here i used the CreateObject() method as shown below:
Set myObj = CreateObject("myDll.myClass")
Now i want to create an object of type myClass from VBScript that is running on another machine, how can i do this. please help me how can i access that dll file, am using the CreateObject() function as shown below:
Set HD = CreateObject("myDll.myClass","myMachineName")
now am getting error as "permission denied".
It appears that this is supported if the assembly is built with as COM visibility enabled.
Is it possible to execute a .NET assembly(dll) from vbscript?
By the way, I was pretty delighted to find out that there is a JScript compiler for .NET which allows one to write .NET code using JScript and also to target other .NET assemblies but unfortunately I haven't found anything similar for VBScript.

Categories