Importing a .pyd file (created with Cython) inside a .py script - python-3.x

I've created a simple .pyd file from my helloWorld.py script using the sample code from here (https://stackoverflow.com/a/36946412/8729576), and although it does generate the .pyd file (along with a build folder, helloWorld.c file) - it throws an error [ImportError: dynamic module does not define module export function (PyInit_helloWorld)] when I attempt to import the function defined inside the original helloWorld.py called printHW using the normal import syntax of:
from helloWorld import printHW
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: dynamic module does not define module export function (PyInit_helloWorld)
helloWorld.py
import time
def printHW():
print("Hello World - today's date is %s"%time.strftime('%Y-%m-%d',time.localtime()))
if '__name__' == '__main__':
printHW()
setup.py
try:
from setuptools import setup
from setuptools import Extension
except ImportError:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension("helloWorld",["helloWorld.py"]) ]
for e in ext_modules:
e.cython_directives = {'language_level' : '3'}
setup(
name= 'helloWorld',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules)
and then in the command prompt enter:
python setup.py build_ext --inplace
I've never worked with Cython before so really not sure what I'm doing wrong here and most SO answers are specific and not generic to what I'm trying to understand (with this basic example).

For anyone else that comes across this error - it has to do with the name of your output file. Playing with the name of the output pyd file and the name provided in the setup.py <[Extension("ThisShallBeYourModuleImportName",["helloWorld.py"]) ]> line I was able to fix my issue (thanks to #DavidW). Observe that whatever name you provide to your .py script in the Extensions list is what you will have to import it as, it is case sensitive. Furthermore, to import the compiled .pyd file 'ThisShallBeYourModuleImportName.cp36-win_amd64.pyd' in your python script, all you need is to say import ThisShallBeYourModuleImportName in your python script and it shall import the module, additionally you can remove the .cp36-win_amd64 and it will still be imported successfully. Try building the above setup.py code with the following changes to observe what I've stated:
try:
from setuptools import setup
from setuptools import Extension
except ImportError:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension("jAckSparroW",["helloWorld.py"]) ]
for e in ext_modules:
e.cython_directives = {'language_level' : '3'}
setup(
name= 'WhatEver',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules)
Now open terminal and try
import jacksparrow
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'jacksparrow'
import jAckSparroW
>>>

Related

Cannot import cython module which is generated using setup.py

I have converted a .pyx file to .pyd using cpython setup.py method but always get the following message :
ValueError: no signature found for builtin <built-in function hello>
The file I am converting test.pyx :
from pyxll import xl_func
#xl_func
def hello():
return "HELLO WORLD"
setup.py script :
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [
Extension("example.test", sources=["example/test.pyx"])
]
setup(
name='Example',
cmdclass={'build_ext': build_ext},
ext_modules=ext_modules
)
When I try to import this test module I get the specified message.
Although when I tried to convert test.pyx without import and decorator it worked so is there any specific configuration change required in setup to include pyxll.
Enviorment : Python 3.8.5 32 bit
As #cvanelteren pointed out file type was the problem I compiled a py file and it fixed the issue of imports

Not able to load python custom module from another directory

I want to load a custom python module from another directory. This question also has been asked many times and I have followed lot of links, and I have a solution. However, it is not working for me. I am fairly new to Python and looks like I am making a simple mistake which I am not able to find.
Below is the hierarchy. I want to import 'extollo_keyvault.py' inside 'testCode.py'. I can see the path for 'extollo_keyvault.py' when I print 'sys.path', however, the script execution fails saying that unable to find that module
Code:
import os
import sys
path_to_extolloKeyvault_module = os.path.join(os.getcwd(), 'extollo_instance', 'hardened', 'extollo_keyvault.py')
sys.path.insert(0, path_to_extolloKeyvault_module)
import extollo_keyvault
Error:
Traceback (most recent call last):
File "c:/Users/manjug/source/repos/extollo-instance-march-31/extollo_instance/Instance/testCode.py", line 6, in <module>
import extollo_keyvault
ModuleNotFoundError: No module named 'extollo_keyvault'
Your current code includes /Instance.
Try this code:
import os
import sys
from pathlib import Path
path = Path(os.getcwd())
path_to_extolloKeyvault_module = os.path.join(path.parent.absolute(), 'extollo-instance-march-31', 'extollo_instance', 'hardened'
sys.path.insert(0, path_to_extolloKeyvault_module)
import extollo_keyvault

Unable to run python script, error shows ModuleNotFoundError: No module named 'src'

Below is the python script(selenium webdriver) I want to execute. But I see error is being thrown that ModuleNotFoundError: No module named 'src'. I see the module src(folder) exist. I am trying to execute this in command prompt. Can some one please help me where I'm doing wrong.
from src.pages.base_page import BasePage
from src.pages.login_page import LoginPage
import unittest
class Dispatcher(BasePage, unittest.TestCase):
def setup(self):
super(Dispatcher,self).setup()
def login_eoc(self):
self.login_page.login()
test output:
C:\NASAuto\tests>py test_dispatcher.py
Traceback (most recent call last):
File "test_dispatcher.py", line 1, in
from src.pages.base_page import BasePage
ModuleNotFoundError: No module named 'src'
run a command line, go to the python folder,
python.exe import src
and verify if python is able to import src. If not try to reinstall this module
Else
You need to add that directory to the path:
import sys
sys.path.append('../src')
Maybe put this into a module if you are using it a lot.
good luck

cx_Freeze ModuleNotFoundError: No module named 'codecs'

Trying to convert a .py file into a .exe
when trying to run the .exe file in the exe.win32-3.6 folder I get the following error:
C:\Users\Aktan\Desktop\build\exe.win32-3.6>StatisticsCalculator.exe
Fatal Python error: Py_Initialize: unable to load the file system codec
Traceback (most recent call last):
File "C:\Users\Aktan\AppData\Local\Programs\Python\Python36-32\lib\encodings\__init__.py", line 31, in <module>
ModuleNotFoundError: No module named 'codecs'
here is my setup.py code:
import cx_Freeze
import sys
import os
import matplotlib
os.environ['TCL_LIBRARY'] = "C:\\LOCAL_TO_PYTHON\\Python35-32\\tcl\\tcl8.6"
os.environ['TK_LIBRARY'] = "C:\\LOCAL_TO_PYTHON\\Python35-32\\tcl\\tcl8.6"
base = None
if sys.platform == 'win32':
base='Win32GUI'
executables = [cx_Freeze.Executable("StatisticsCalculator.py", base=None)]
cx_Freeze.setup(
name="This is a tes",
options = {"build_exe": {"packages":["numpy"]}},
version = "0.01",
description = "Trying to get this to work",
executables = executables
)
and I do not know if it helps, but here are the modules I use in my python program:
import sqlite3
from math import pow, sqrt
from tkinter import Tk, Label, Listbox, END, Button, Message, messagebox
import matplotlib.pyplot as plt
I have python 3.6.3 and I am running Windows 10. Any response would be appreciated.
This is a known issue with cx_Freeze which has been resolved in the source. A new release (5.1.1) will be out shortly to correct that issue!

ImportError pyramid hello world program

source code:
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
def hello_world(request):
return Response('<h1>Hello world!</h1>')
if __name__ == '__main__':
config = Configurator()
config.add_view(hello_world)
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 8080, app)
server.serve_forever()
When I ran the sample hello_world program using pyramid, I got the following error.
Traceback (most recent call last):
File "application.py", line 2, in <module>
from pyramid.config import Configurator
File "/usr/local/lib/python2.7/dist-packages/pyramid/config/__init__.py", line 12, in <module>
from pyramid.interfaces import (
File "/usr/local/lib/python2.7/dist-packages/pyramid/interfaces.py", line 3, in <module>
from zope.interface import (
ImportError: No module named interface
You've installed something improperly - more than likely by using python setup.py develop somewhere instead of using pip install -e .. If you mix tools you're going to have some issues. This particular one seems to be due to namespace packages not being configured correctly which almost always is a symptom of using easy_install and pip in the same environment. You need to pick one (preferably pip), and sometimes the decision about which one to use was already made by whatever tool installed python for you.

Resources