|
| 1 | +`pythonnet` is a package that gives .NET programmers ability to |
| 2 | +integrate Python engine and use Python libraries. |
| 3 | + |
| 4 | +##Embedding Python in .NET |
| 5 | + |
| 6 | +- You must set`Runtime.PythonDLL` property or`PYTHONNET_PYDLL` environment variable, |
| 7 | + otherwise you will receive`BadPythonDllException` |
| 8 | + (internal, derived from`MissingMethodException`) upon calling`Initialize`. |
| 9 | + Typical values are`python38.dll` (Windows),`libpython3.8.dylib` (Mac), |
| 10 | +`libpython3.8.so` (most other*nix). Full path may be required. |
| 11 | +- All calls to Python should be inside a |
| 12 | +`using (Py.GIL()) {/* Your code here */}` block. |
| 13 | +- Import python modules using`dynamic mod = Py.Import("mod")`, then |
| 14 | + you can call functions as normal, eg`mod.func(args)`. |
| 15 | + You can also access Python objects via`PyObject` and dervied types |
| 16 | + instead of using`dynamic`. |
| 17 | +- Use`mod.func(args, Py.kw("keywordargname", keywordargvalue))` or |
| 18 | +`mod.func(args, keywordargname: keywordargvalue)` to apply keyword |
| 19 | + arguments. |
| 20 | +- Mathematical operations involving python and literal/managed types |
| 21 | + must have the python object first, eg.`np.pi * 2` works, |
| 22 | +`2 * np.pi` doesn't. |
| 23 | + |
| 24 | +##Example |
| 25 | + |
| 26 | +```csharp |
| 27 | +usingvar_=Py.GIL(); |
| 28 | + |
| 29 | +dynamicnp=Py.Import("numpy"); |
| 30 | +Console.WriteLine(np.cos(np.pi*2)); |
| 31 | + |
| 32 | +dynamicsin=np.sin; |
| 33 | +Console.WriteLine(sin(5)); |
| 34 | + |
| 35 | +doublec= (double)(np.cos(5)+sin(5)); |
| 36 | +Console.WriteLine(c); |
| 37 | + |
| 38 | +dynamica=np.array(newList<float> {1,2,3 }); |
| 39 | +Console.WriteLine(a.dtype); |
| 40 | + |
| 41 | +dynamicb=np.array(newList<float> {6,5,4 },dtype:np.int32); |
| 42 | +Console.WriteLine(b.dtype); |
| 43 | + |
| 44 | +Console.WriteLine(a*b); |
| 45 | +Console.ReadKey(); |
| 46 | +``` |
| 47 | + |
| 48 | +Output: |
| 49 | + |
| 50 | +``` |
| 51 | +1.0 |
| 52 | +-0.958924274663 |
| 53 | +-0.6752620892 |
| 54 | +float64 |
| 55 | +int32 |
| 56 | +[ 6. 10. 12.] |
| 57 | +``` |
| 58 | + |
| 59 | + |
| 60 | + |
| 61 | +##Resources |
| 62 | + |
| 63 | +Information on installation, FAQ, troubleshooting, debugging, and |
| 64 | +projects using pythonnet can be found in the Wiki: |
| 65 | + |
| 66 | +https://github.com/pythonnet/pythonnet/wiki |
| 67 | + |
| 68 | +Mailing list |
| 69 | +https://mail.python.org/mailman/listinfo/pythondotnet |
| 70 | +Chat |
| 71 | +https://gitter.im/pythonnet/pythonnet |
| 72 | + |
| 73 | +###.NET Foundation |
| 74 | + |
| 75 | +This project is supported by the[.NET Foundation](https://dotnetfoundation.org). |