pythonpywin32python.net

How to import win32api from pywin32 when running pythonnet in a c#/.NET environment?


I am working on integrating Python with a C#/.NET runtime using pythonnet, but I keep encountering a module import error with win32api. The error message is "No module named 'win32api'." I have already taken several troubleshooting steps but haven't resolved the issue.

What I've tried:

  1. Verified environment paths.
  2. Ran a test script with Python (outside of .NET), which worked without any issues.
  3. Created a virtual environment (venv).
  4. Added the path venv\Lib\site-packages\pywin32_system32 to both PYTHONPATH and PATH variables.

These paths include the location of two crucial DLLs, but this has not resolved the error. Additional paths added to the system environment include venv\Lib\site-packages and Python\Python310\DLLs.

Additional context from GitHub discussion:

@filmor mentioned ensuring that PATH and PYTHONPATH settings are correct. However, I cannot find out which specific paths are necessary for pywin32 to function properly in this context, as other modules like numpy in the venv work correctly.

Question:

Are there specific directories or DLLs or even other files that must be included in the PATH or PYTHONPATH for pywin32 to be recognized by pythonnet?

The goal is to get TensorRT running, which has a win32api import somewhere deep inside. Any insights or suggestions would be greatly appreciated. Thank you!

Edit: I have also run the pywin32_postinstall.py script as admin and the two DLLs are in Sytemem32. As a simple test script works well with Python in Powershell, I think it is some special issue with pythonnet. Anyone has any idea?


Solution

    1. Copy the two dlls from venv\Lib\site-packages\pywin32_system32 to C:\Windows\System32

    or Run as administrator

    $ python .\venv\Scripts\pywin32_postinstall.py -install
    
    1. add

    to PYTHONPATH