9

I'm writing C++ code which should invoke python scripts underneath. For this purpose I use cpython of python.org. Some of the python scripts execute .net code with help of python for .net and when it comes to .net all this fails. I tried to build test app to verify where it fails and found that it can't import clr module.

When I run this code it give me ImportError: No module named clr

Py_Initialize();
PyRun_SimpleString("import clr");

If I go to python console and type "import clr" everything works fine. I also checked sys.path and it contains the folder where clr.pyd located 'C:\Python27\DLLs'. I also tried setting this path in C++ by:

char* path = "C:\\Python27\\dlls";
Py_Initialize();
PySys_SetArgv(1, &path);
char* phome = Py_GetPythonHome();

But it didn't helped. In addition I don't understand why clr module is appears as clr.pyd and not .pyc like other compiled modules.

Could someone can explain why import clr fails through CPython? Is it possible to make it work?

denfromufa
  • 5,610
  • 13
  • 81
  • 138
y_d
  • 91
  • 1
  • 1
  • 3

4 Answers4

18

To install clr, you have to install pythonnet library.

You can install pythonnet using following command.

 pip install pythonnet
jatinkumar patel
  • 2,920
  • 21
  • 28
1

You need to call PySys_SetArgv after Py_Initialize appropriately to change the syspath.

mic4ael
  • 7,974
  • 3
  • 29
  • 42
1

I work behind a proxy server with multiple versions of python. I have a bat file I update when I need a new module, or wish to update an existing one. The first line sets the path to the version I wish to update The bat file is run from the scripts directory. Proxy IP with port "9.254.0.1:81"

SET path="C:\Programs\Python\Python3_64"
pip install --proxy="9.254.0.1:81" --upgrade pip
pip install --proxy="9.254.0.1:81" pythonnet
Bill Kidd
  • 1,130
  • 11
  • 13
0

This error is most commonly caused by having multiple Python installations that may (or may not) be part of you (Windows) system PATH variable. When you start your Powershell, it will use that PATH, depending on:

  1. The order placement in the (Windows) System PATH.
    (Does your Python3.7 come before Python3.8?)
  2. If you have other Python interpreters installed, such as:
    conda, miniconda3, etc., which have their own paths.

Then when you do pip install pythonnet, the package will be installed in the system package location, depending on which pip you are using. Check with pip -V.

For example:
If you find your default shell to starting with conda activated, you need to do conda deactivate before you do your pip install.

(base)  $ pip -V
pip 20.2.4 from c:\users\xxxx\miniconda3\lib\site-packages\pip (python 3.7)

(base)  $ conda deactivate
$ pip -V
pip 20.2.4 from c:\python38\lib\site-packages\pip (python 3.8)
not2qubit
  • 14,531
  • 8
  • 95
  • 135