cv loading for executable - python

I had imported cv2 library in my code and made an executable by using py2exe through GUI2EXE software.
Py2exe has created cv2.pyc file which is run every time the application is started and creates an error of 'Import Error: DLL load failed.Cannot find the module specified' at line mod = imp.load_dynamic(name,path). It has also made other files like numpy.core_sort which give the same error when run.
My question is that py2exe is only running the cv2.pyc file while running the application. Why is it doing so? It should have just imported the cv2 library.
The code in the cv2.pyc file is given below
def __load():
import imp, os, sys
try:
dirname = os.path.dirname(__loader__.archive)
except NameError:
dirname = sys.prefix
path = os.path.join(dirname, 'cv2.pyd')
#print "py2exe extension module", __name__, "->", path
mod = imp.load_dynamic(__name__, path)
## mod.frozen = 1
__load()
del __load
My code calls libraries in this manner :-
import wx
import wx.lib.buttons
import numpy as np
import os
import cv2.cv as cv #Import functions from OpenCV
from numpy import *
from PIL import Image #python imaging library

Looking at cv2.cpp it has #include "numpy/ndarrayobject.h"
so it looks like it loads numpy, which is not surprising.
As py2exe does not see the c++ source code, it will not detect this. So I think "the module specified" that can't be found is numpy.
Adding the following line to your setup.py should fix your problem:
import numpy

Related

OSError when trying to use a C-based library in Python with ctypes (Windows)

I'm currently trying to use a library written in C with my Python code but I didn't have much success at all. I'm currently using Windows and have downloaded, saved and installed the library (linked below) to a directory near my project using Cygwin.
As of now, I'm not sure how you load it within your Python code. I followed the instruction in this link: https://github.com/xiph/rnnoise/issues/69 but replaced the library path with a relative path and saved the library inside my project directory. Here's my code and here's the return error
import wave
import os,sys
import ctypes
import contextlib
import numpy as np
from ctypes import util
from scipy.io import wavfile
from pydub import AudioSegment
lib_path = "rnnoise"
lib = ctypes.cdll.LoadLibrary(lib_path)
Here's the version from the instruction:
import wave
import os,sys
import ctypes
import contextlib
import numpy as np
from ctypes import util
from scipy.io import wavfile
from pydub import AudioSegment
lib_path = util.find_library("rnnoise")
if (not("/" in lib_path)):
lib_path = (os.popen('ldconfig -p | grep '+lib_path).read().split('\n')[0].strip().split(" ")[-1] or ("/usr/local/lib/"+lib_path))
lib = ctypes.cdll.LoadLibrary(lib_path)
Traceback (most recent call last):
File "c:/Users/duyba/Documents/CET/Project/vadtest/noisetest.py", line 14, in <module>
lib = ctypes.cdll.LoadLibrary(lib_path)
File "C:\Users\duyba\anaconda3\lib\ctypes\__init__.py", line 459, in LoadLibrary
return self._dlltype(name)
File "C:\Users\duyba\anaconda3\lib\ctypes\__init__.py", line 381, in __init__
self._handle = _dlopen(self._name, mode)
OSError: [WinError 1920] The file cannot be accessed by the system
My impression of the instruction version was that they are trying to locate the library in Linux, so I just copied the library to the project folder and didn't know what they are trying to load once the library is located. Also, I think that some environment pathway problems may be at play here since I downloaded and installed this library in Windows.
The library: https://github.com/xiph/rnnoise.
Thanks.
This could be an file access permission error. You might be able to get around it by making a new virtual environment or by uninstalling and reinstalling Python; see this post.

Cannot run my .exe python program using cx_freeze

I wrote a program where I imported those lib :
from math import*
from pylab import*
import numpy as np
import matplotlib
import matplotlib.backends.backend_tkagg
import numpy as np
import matplotlib.pyplot as plt
and I wanted to make an executable out of it (the .py already runs using pylab) so in the Windows terminal (in the Python's script folder) I did the command cxfreeze solver.py : this creates a solver.exe in Dist folder.
When I tried to run this executable, there is :
File "C:\Users\*****\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 35, in <module>
import _tkinter # If this fails your Python may not be configured for Tk
ImportError: DLL load failed: Le module spécifié est introuvable.
In english : the specified module is not found
I read several help on the site and on internet but it nerver fixed it, and after few days of searching I begin to give up. Please help !

Embedding FreeCAD in python script

I am trying to run FreeCAD modules from a python script. Here is the code I have written to import the FreeCAD modules according with this tutorial" (eventhoug I don't have any FreeCAD.dll installed on my HD):
FREECADPATH = "C:\\Program Files (x86)\\FreeCAD 0.16\\bin"
import sys
sys.path.append(FREECADPATH)
import FreeCAD
import Part
import Mesh
...then the FreeCAD commands
But i got the following error:
" import Part
ImportError: No module named Part"
I also tried with a 64bit version of the FreeCAD
C:\Program Files\FreeCAD 0.16\bin
Any suggestion?

Error "No such file or directory" when i import a ".so" file and that file is available in python

I have a python code and some nao files(naoqi.py,_inaoqi.so, ...) in a folder in a raspberry pi 3 model B v1.2 with armv7l. my code has some import line:
import sys
from naoqi import ALProxy
import time
import almath
import os
import socket
when i run this code i see "cannot open shared object file: No such file or directory" error from second line :
from naoqi import ALProxy
and in below line in naoqi.py (in line import _inaoqi):
try:
import _inaoqi
except ImportError:
# quick hack to keep inaoqi.py happy
if sys.platform.startswith("win"):
print "Could not find _inaoqi, trying with _inaoqi_d"
import _inaoqi_d as _inaoqi
else:
raise
this file is available, but i see "cannot open shared object file: No such file or directory" error.
Why such an error occurs.
What can i do?
Just dumping the inaoqi files into your program directory isn't sufficient, you have to package them properly as a "python module." Is there an installer available for an inaoqi package, or can it be installed using pip?
Also, if you're running Python on Windows, the .so file isn't going to do you any good. The C or C++ code for the module on Windows will be in a .dll file, so again, check to see if an installer for the module is available for your platform.

Can't import comtypes.gen

I have comtypes 0.6.2 installed on Python 2.6. If I try this:
import comtypes.gen
I get:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
import comtypes.gen
ImportError: No module named gen
Other imports like import comtypes and import comtypes.client, however, work fine.
What am I doing wrong?
From the name it seems comtypes.gen is generated code? If so, do I need certain preparatory steps before importing? I'm not logged in as administrator. Could that cause code generation to fail?
Edit:
The above problem is solved with a reload(comtypes.gen) (I don't understand how, though). However, now from comtypes.gen import IWshRuntimeLibrary is not working. This symbol should be part of a generated code. So how do I get this code to be generated?
Well, after some experimentation, I have the solution.
I've found that:
Importing comtypes.client automatically creates the comtypes.gen subpackage.
Calling comtypes.client.GetModule("MyComLib") generates a wrapper for "MyComLib".
So the following code did the job for me:
import os
import glob
import comtypes.client
#Generates wrapper for a given library
def wrap(com_lib):
try:
comtypes.client.GetModule(com_lib)
except:
print "Failed to wrap {0}".format(com_lib)
sys32dir = os.path.join(os.environ["SystemRoot"], "system32")
#Generate wrappers for all ocx's in system32
for lib in glob.glob(os.path.join(sys32dir, "*.ocx")):
wrap(lib)
#Generate for all dll's in system32
for lib in glob.glob(os.path.join(sys32dir, "*.tlb")):
wrap(lib)
Having the relevant COM lib wrapped, now I can access IWshRuntimeLibrary just fine.
Perhaps, as it says, the package gen package in comptypes doesn't exist. Check your site-packages folder (C:\Python26\Lib\site-packages on Windows, substitute the C:\Python26 with your installation directory) for a comtypes\gen subfolder.
recently i got the new office, and i had to extend the script of #frederick to generate all the office objects again.
import os
import glob
import comtypes.client
# You may want to change the office path
msoffice=r'C:\Program Files (x86)\Microsoft Office\root\Office16'
#Generates wrapper for a given library
def wrap(com_lib):
try:
comtypes.client.GetModule(com_lib)
except:
print("Failed to wrap {0}".format( com_lib))
sys32dir = os.path.join(os.environ["SystemRoot"], "system32")
#Generate wrappers for all ocx's in system32
for lib in glob.glob(os.path.join(sys32dir, "*.ocx")):
wrap(lib)
#Generate for all dll's in system32
for lib in glob.glob(os.path.join(msoffice, "*.tlb")):
wrap(lib)
for lib in glob.glob(os.path.join(msoffice, "*.olb")):
wrap(lib)
# And a special case for Excel
excel=os.path.join(msoffice,"excel.exe")
wrap(excel)

Categories

Resources