Pyusb on Windows 7 - NotImplemented Error :is_kernal_driver_active - windows

I am using escposprinter python library for printing my data in thermal printer. It depends on pyusb. the library is working fine in linux . While in windows 7 ,i get the it have some issues. Here are output i get.
File "main.py", line 1, in <module>
from app import app
File "D:\freeth-in-erp-60ab8eb96fad\app\__init__.py", line 94, in <module>
from .api_routes import *
File "D:\freeth-in-erp-60ab8eb96fad\app\api_routes.py", line 44, in <module>
from .printer import pos
File "D:\freeth-in-erp-60ab8eb96fad\app\printer\pos.py", line 14, in <module>
Epson = printer.Usb(idVendor=0x0416,idProduct=0x5011)
File "D:\freeth-in-erp-60ab8eb96fad\venv\lib\site-packages\escposprinter\print
er.py", line 37, in __init__
self.open()
File "D:\freeth-in-erp-60ab8eb96fad\venv\lib\site-packages\escposprinter\print
er.py", line 46, in open
if self.device.is_kernel_driver_active(0):
File "D:\freeth-in-erp-60ab8eb96fad\venv\lib\site-packages\usb\core.py", line
1064, in is_kernel_driver_active
interface)
File "D:\freeth-in-erp-60ab8eb96fad\venv\lib\site-packages\usb\backend\__init_
_.py", line 365, in is_kernel_driver_active
_not_implemented(self.is_kernel_driver_active)
File "D:\freeth-in-erp-60ab8eb96fad\venv\lib\site-packages\usb\backend\__init_
_.py", line 81, in _not_implemented
raise NotImplementedError(func.__name__)
NotImplementedError: is_kernel_driver_active
i download the libusb-1.20 from libusb.info and copy file libusb-1.0.dll from MinGW32 and paste in "C:\windows\System32". I get the following result.
from app import app
File "D:\freeth-in-erp-60ab8eb96fad\app\__init__.py", line 94, in <module>
from .api_routes import *
File "D:\freeth-in-erp-60ab8eb96fad\app\api_routes.py", line 44, in <module>
from .printer import pos
File "D:\freeth-in-erp-60ab8eb96fad\app\printer\pos.py", line 14, in <module>
Epson = printer.Usb(idVendor=0x0416,idProduct=0x5011)
File "D:\freeth-in-erp-60ab8eb96fad\venv\lib\site-packages\escposprinter\print
er.py", line 37, in __init__
self.open()
File "D:\freeth-in-erp-60ab8eb96fad\venv\lib\site-packages\escposprinter\print
er.py", line 46, in open
if self.device.is_kernel_driver_active(0):
File "D:\freeth-in-erp-60ab8eb96fad\venv\lib\site-packages\usb\core.py", line
1064, in is_kernel_driver_active
interface)
File "D:\freeth-in-erp-60ab8eb96fad\venv\lib\site-packages\usb\backend\libusb1
.py", line 898, in is_kernel_driver_active
intf)))
File "D:\freeth-in-erp-60ab8eb96fad\venv\lib\site-packages\usb\backend\libusb1
.py", line 593, in _check
raise NotImplementedError(_strerror(ret))
NotImplementedError: Operation not supported or unimplemented on this platform
my code is
`
from escposprinter import *
from tabulate import tabulate
Epson = printer.Usb(0x0416,0x5011)
from library escposprinter
class Usb(Escpos):
""" Define USB printer """
def __init__(self, idVendor, idProduct, interface=0, in_ep=0x82, out_ep=0x01):
"""
#param idVendor : Vendor ID
#param idProduct : Product ID
#param interface : USB device interface
#param in_ep : Input end point
#param out_ep : Output end point
"""
self.idVendor = idVendor
self.idProduct = idProduct
self.interface = interface
self.in_ep = in_ep
self.out_ep = out_ep
self.open()
def open(self):
""" Search device on USB tree and set is as escpos device """
self.device = usb.core.find(idVendor=self.idVendor, idProduct=self.idProduct)
if self.device is None:
print ("Cable isn't plugged in")
if self.device.is_kernel_driver_active(0):
try:
self.device.detach_kernel_driver(0)
except usb.core.USBError as e:
print ("Could not detatch kernel driver: %s" % str(e))
help me with your suggestion
`

The problem is plain and simple that the check whether a kernel driver is active which is not possible on Windows. It seems this library is simply not written for use on Windows.
You can use it on Windows if you delete the last 5 lines from the source code starting with if self.device.is_kernel_driver_active(0): or check if the code runs on Windows beforehand and don't call them.
Remember on Windows you need to install your own driver. I recommend using Zadig for creating and/or installing the driver.

Related

Sentiment anaysis using Harvard IV-4 dictionary

I was trying to compute the sentiment using Harvard IV-4dictionary.
I installed the "pysentiment" successfully.
I run the following:
import pysentiment as ps
hiv4 = ps.HIV4()
tokens = hiv4.tokenize(text)
score = hiv4.get_score(tokens)
and I got the following error:
Traceback (most recent call last):
File "C:/Users/df/Desk Top/Finalazed/punctuation.py", line 274, in <module>
hiv4 = ps.HIV4()
File "C:\Users\df\AppData\Local\Programs\Python\Python37\lib\site-packages\pysentiment\base.py", line 55, in __init__
self._tokenizer = Tokenizer()
File "C:\Users\df\AppData\Local\Programs\Python\Python37\lib\site-packages\pysentiment\utils.py", line 36, in __init__
self._stopset = self.get_stopset()
File "C:\Users\df\AppData\Local\Programs\Python\Python37\lib\site-packages\pysentiment\utils.py", line 52, in get_stopset
fin = open('%s/%s'%(STATIC_PATH, f), 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\df\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages\\pysentiment\\static/Currencies.txt'
Could any body tell why I am getting this? Thanks.
Do copy pysentiment folder in the given path. Actually pysentiment folder doesnt contain static sub folder. You can check it by diplaying hidden folder "local".

Error the deployment function in lambda with graphene module

error when executing the function in aws lambda, while locally there is no error.
When executing the code in AWS lambda this error arises, what I want is to be able to use graqpl to perform dynamodb queries and to use them.
Solution attempt: uninstall typing from the python virtual environment.
Error that occurs:
[ERROR] AttributeError: type object 'Callable' has no attribute '_abc_registry'
Traceback (most recent call last):
File "/var/lang/lib/python3.7/imp.py", line 234, in load_module
return load_source(name, filename, file)
File "/var/lang/lib/python3.7/imp.py", line 171, in load_source
module = _load(spec)
File "<frozen importlib._bootstrap>", line 696, in _load
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/var/task/patron4.py", line 7, in <module>
import graphene
File "/tmp/sls-py-req/graphene/__init__.py", line 3, in <module>
from .types import (
File "/tmp/sls-py-req/graphene/types/__init__.py", line 2, in <module>
from graphql import ResolveInfo
File "/tmp/sls-py-req/graphql/__init__.py", line 27, in <module>
from .graphql import graphql
File "/tmp/sls-py-req/graphql/graphql.py", line 1, in <module>
from .execution import ExecutionResult
File "/tmp/sls-py-req/graphql/execution/__init__.py", line 21, in <module>
from .executor import execute, subscribe
File "/tmp/sls-py-req/graphql/execution/executor.py", line 14, in <module>
from promise import Promise, promise_for_dict, is_thenable
File "/tmp/sls-py-req/promise/__init__.py", line 18, in <module>
from .promise import (
File "/tmp/sls-py-req/promise/promise.py", line 8, in <module>
from typing import (List, Any, Callable, Dict, Iterator, Optional, # flake8: noqa
File "/tmp/sls-py-req/typing.py", line 1357, in <module>
class Callable(extra=collections_abc.Callable, metaclass=CallableMeta):
File "/tmp/sls-py-req/typing.py",enter code here line 1005, in __new__
self._abc_registry = extra._abc_registry
Code used:
class User(Model):
class Meta:
table_name = 'patron2'
region = 'us-east-2'
host = 'https://dynamodb.us-east-2.amazonaws.com'
id = UnicodeAttribute(hash_key=True, null=False)
discipline = UnicodeAttribute(null=False)
class UserNode(PynamoObjectType):
class Meta:
model = User
interfaces = (graphene.Node,)
class Query(graphene.ObjectType):
users = graphene.List(UserNode)
def resolve_users(self, args, context, info):
return list(User.scan())
schema = graphene.Schema(query=Query)
def patrongrafico(event, context):
# fetch all todos from the database
try:
print("hola")
query = '''
users {
discipline
}
'''
results = schema.execute(query)
print(results)
except Exception as ex:
print(ex)
return {'statusCode': 200,
'body': json.dumps({'items': [dict(result) for result in results]})}
Since you're using the Serverless Framework in combination with the serverless-python-requirements plugin you should make sure, that slim packaging is off, as this interferes with some libraries. Essentially some libraries assume they're installed via a "real" package manager and in that case the directory layout and files look slightly different.
I was having this problem with the jsonschema package a few months ago and wrote about it in a blog post if you're interested (Full disclosure: this is the blog of my employer).
Essentially your serverless.yml as a custom section which you can use among other things to configure the plugins:
custom:
pythonRequirements:
slim: true
The slim true parameter effectively removes some information that shouldn't be necessary for most libraries, but some rely on it. For information on this parameter see the package's docs.
Try again with this configuration:
custom:
pythonRequirements:
slim: false
The solution to the error is to remove the version of Python 3.7 and implement 3.6, since Graphene does not support versions greater than 3.6.

IOError: [Errno 1] Operation not permitted: '/dev/uinput'

I seem to have some problems let python read key event, I wrote this piece of code
for recording while i have space down and stop when i've release it..
import pyaudio
import wave
import keyboard
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("* recording")
frames = []
while keyboard.is_pressed('space'):
data = stream.read(CHUNK)
frames.append(data)
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
But when running this code, I get this error message.
python sound_record.py
* recording
Traceback (most recent call last):
File "sound_record.py", line 24, in <module>
while keyboard.is_pressed('space'):
File "/usr/local/lib/python2.7/site-packages/keyboard/__init__.py", line 162, in is_pressed
_listener.start_if_necessary()
File "/usr/local/lib/python2.7/site-packages/keyboard/_generic.py", line 36, in start_if_necessary
self.init()
File "/usr/local/lib/python2.7/site-packages/keyboard/__init__.py", line 112, in init
_os_keyboard.init()
File "/usr/local/lib/python2.7/site-packages/keyboard/_nixkeyboard.py", line 110, in init
build_device()
File "/usr/local/lib/python2.7/site-packages/keyboard/_nixkeyboard.py", line 106, in build_device
ensure_root()
File "/usr/local/lib/python2.7/site-packages/keyboard/_nixcommon.py", line 163, in ensure_root
raise ImportError('You must be root to use this library on linux.')
ImportError: You must be root to use this library on linux.
And when i do it using sudo:
sudo !!
sudo python sound_record.py
Password:
* recording
Traceback (most recent call last):
File "sound_record.py", line 24, in <module>
while keyboard.is_pressed('space'):
File "/usr/local/lib/python2.7/site-packages/keyboard/__init__.py", line 162, in is_pressed
_listener.start_if_necessary()
File "/usr/local/lib/python2.7/site-packages/keyboard/_generic.py", line 36, in start_if_necessary
self.init()
File "/usr/local/lib/python2.7/site-packages/keyboard/__init__.py", line 112, in init
_os_keyboard.init()
File "/usr/local/lib/python2.7/site-packages/keyboard/_nixkeyboard.py", line 110, in init
build_device()
File "/usr/local/lib/python2.7/site-packages/keyboard/_nixkeyboard.py", line 107, in build_device
device = aggregate_devices('kbd')
File "/usr/local/lib/python2.7/site-packages/keyboard/_nixcommon.py", line 141, in aggregate_devices
uinput = make_uinput()
File "/usr/local/lib/python2.7/site-packages/keyboard/_nixcommon.py", line 27, in make_uinput
uinput = open("/dev/uinput", 'wb')
IOError: [Errno 1] Operation not permitted: '/dev/uinput'
So why am I getting this error message?
You appear to be using the Python package keyboard, whose description is:
Hook and simulate keyboard events on Windows and Linux
If you want to do work with keyboard events on MacOS, you'll need to find a package that does that.

ipython notebook installation on mac os x

I am wondering if anyone has installed ipython notebook on mac OSX?
Currently I am able to run it in the terminal note but as soon as I type in the notebook version, there are problems encountered in running it.
Below is the error I have gotten:
Traceback (most recent call last): File
"/Users/tayyangki/anaconda/bin/ipython", line 9, in
load_entry_point('ipython==2.0.0-dev', 'console_scripts', 'ipython')() File
"/Users/tayyangki/anaconda/lib/python2.7/site-packages/ipython-2.0.0_dev-py2.7.egg/IPython/init.py",
line 118, in start_ipython
return launch_new_instance(argv=argv, **kwargs) File "/Users/tayyangki/anaconda/lib/python2.7/site-packages/ipython-2.0.0_dev-py2.7.egg/IPython/config/application.py",
line 565, in launch_instance
app.initialize(argv) File "", line 2, in initialize File
"/Users/tayyangki/anaconda/lib/python2.7/site-packages/ipython-2.0.0_dev-py2.7.egg/IPython/config/application.py",
line 92, in catch_config_error
return method(app, *args, **kwargs) File "/Users/tayyangki/anaconda/lib/python2.7/site-packages/ipython-2.0.0_dev-py2.7.egg/IPython/terminal/ipapp.py",
line 314, in initialize
super(TerminalIPythonApp, self).initialize(argv) File "", line 2, in initialize File
"/Users/tayyangki/anaconda/lib/python2.7/site-packages/ipython-2.0.0_dev-py2.7.egg/IPython/config/application.py",
line 92, in catch_config_error
return method(app, *args, **kwargs) File "/Users/tayyangki/anaconda/lib/python2.7/site-packages/ipython-2.0.0_dev-py2.7.egg/IPython/core/application.py",
line 371, in initialize
self.parse_command_line(argv) File "/Users/tayyangki/anaconda/lib/python2.7/site-packages/ipython-2.0.0_dev-py2.7.egg/IPython/terminal/ipapp.py",
line 309, in parse_command_line
return super(TerminalIPythonApp, self).parse_command_line(argv) File "", line 2, in parse_command_line File
"/Users/tayyangki/anaconda/lib/python2.7/site-packages/ipython-2.0.0_dev-py2.7.egg/IPython/config/application.py",
line 92, in catch_config_error
return method(app, *args, **kwargs) File "/Users/tayyangki/anaconda/lib/python2.7/site-packages/ipython-2.0.0_dev-py2.7.egg/IPython/config/application.py",
line 474, in parse_command_line
return self.initialize_subcommand(subc, subargv) File "", line 2, in initialize_subcommand File
"/Users/tayyangki/anaconda/lib/python2.7/site-packages/ipython-2.0.0_dev-py2.7.egg/IPython/config/application.py",
line 92, in catch_config_error
return method(app, *args, **kwargs) File "/Users/tayyangki/anaconda/lib/python2.7/site-packages/ipython-2.0.0_dev-py2.7.egg/IPython/config/application.py",
line 405, in initialize_subcommand
subapp = import_item(subapp) File "/Users/tayyangki/anaconda/lib/python2.7/site-packages/ipython-2.0.0_dev-py2.7.egg/IPython/utils/importstring.py",
line 42, in import_item
module = import(package, fromlist=[obj]) File "/Users/tayyangki/anaconda/lib/python2.7/site-packages/ipython-2.0.0_dev-py2.7.egg/IPython/html/notebookapp.py",
line 75, in
from IPython.consoleapp import IPythonConsoleApp File "/Users/tayyangki/anaconda/lib/python2.7/site-packages/ipython-2.0.0_dev-py2.7.egg/IPython/consoleapp.py",
line 43, in
from IPython.kernel.zmq.kernelapp import ( File "/Users/tayyangki/anaconda/lib/python2.7/site-packages/ipython-2.0.0_dev-py2.7.egg/IPython/kernel/zmq/kernelapp.py",
line 54, in
from .ipkernel import Kernel File "/Users/tayyangki/anaconda/lib/python2.7/site-packages/ipython-2.0.0_dev-py2.7.egg/IPython/kernel/zmq/ipkernel.py", line 40, in
from .zmqshell import ZMQInteractiveShell File "/Users/tayyangki/anaconda/lib/python2.7/site-packages/ipython-2.0.0_dev-py2.7.egg/IPython/kernel/zmq/zmqshell.py", line 36, in
from IPython.core.payloadpage import install_payload_page File "/Users/tayyangki/anaconda/lib/python2.7/site-packages/ipython-2.0.0_dev-py2.7.egg/IPython/core/payloadpage.py",
line 24, in
from docutils.core import publish_string File "/Users/tayyangki/anaconda/lib/python2.7/site-packages/docutils/core.py",
line 20, in
from docutils import frontend, io, utils, readers, writers File "/Users/tayyangki/anaconda/lib/python2.7/site-packages/docutils/frontend.py",
line 41, in
import docutils.utils File "/Users/tayyangki/anaconda/lib/python2.7/site-packages/docutils/utils/init.py",
line 20, in
import docutils.io File "/Users/tayyangki/anaconda/lib/python2.7/site-packages/docutils/io.py",
line 18, in
from docutils.utils.error_reporting import locale_encoding, ErrorString, ErrorOutput File
"/Users/tayyangki/anaconda/lib/python2.7/site-packages/docutils/utils/error_reporting.py",
line 47, in
locale_encoding = locale.getlocale()[1] or locale.getdefaultlocale()[1] File
"/Users/tayyangki/anaconda/lib/python2.7/locale.py", line 511, in
getdefaultlocale
return _parse_localename(localename) File "/Users/tayyangki/anaconda/lib/python2.7/locale.py", line 443, in
_parse_localename
raise ValueError, 'unknown locale: %s' % localename ValueError: unknown locale: UTF-8
Greatly appreciated if someone could help me?
As noted here, the workaround for the "unknown locale: UTF-8" issue to add:
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
to your to your ~/.bash_profile.
thanks for the info but I have found out the problems a few weeks ago and have forgotten to post it here....
It is just that for Mac installation, it is pretty tricky and hence while installing, instead of typing in: easy_install ipython, users have to specify the python version.
Thus, I will need to type in easy_install ipython2.7
After which all is fine and working great!

Error 1053 When Starting Window Service Written In Python

I have already looked at and tried the resolutions to this question that others have posted. One user said that to try and change my setup.py file from:
from distutils.core import setup
import py2exe
setup(console=["dev.py"])
to
from distutils.core import setup
import py2exe
setup(service=["dev.py"])
I got the following results:
running py2exe
*** searching for required modules ***
Traceback (most recent call last):
File "C:\Python27\Scripts\distutils-setup.py", line 5, in <module>
setup(service=["C:\Python27\Scripts\dev.py"])
File "C:\Python27\lib\distutils\core.py", line 152, in setup
dist.run_commands()
File "C:\Python27\lib\distutils\dist.py", line 953, in run_commands
self.run_command(cmd)
File "C:\Python27\lib\distutils\dist.py", line 972, in run_command
cmd_obj.run()
File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 243, in run
self._run()
File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 296, in _run
self.find_needed_modules(mf, required_files, required_modules)
File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 1274, in
find_needed_modules
mf.import_hook(mod)
File "C:\Python27\lib\site-packages\py2exe\mf.py", line 719, in import_hook
return Base.import_hook(self,name,caller,fromlist,level)
File "C:\Python27\lib\site-packages\py2exe\mf.py", line 136, in import_hook
q, tail = self.find_head_package(parent, name)
File "C:\Python27\lib\site-packages\py2exe\mf.py", line 204, in find_head_package
raise ImportError, "No module named " + qname
ImportError: No module named dev
Now, when I run py2exe with "console" in my setup script it works fine, but the service doesn't start and I get the error. When I run py2exe with "service" in my setup script py2exe doesn't run and tells me it can't find my module.
I have tried to re-install py2exe to no resolution. I have also tried to change:
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
to
def SvcDoRun(self):
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
Didn't make a difference either. CAN ANYONE HELP ME PLEASE? Here is what I am working on. It monitors a server and spits back a text file every 60 seconds which I use to monitor my servers at any given minute. Any help you guys and gals can give would be great.
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import wmi
import _winreg
from time import sleep
import os
class SrvMonSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "SrvMonSvc"
_svc_display_name_ = "Server Monitor"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def main(self):
host = wmi.WMI(namespace="root/default").StdRegProv
try:
result, api = host.GetStringValue(
hDefKey = _winreg.HKEY_LOCAL_MACHINE,
sSubKeyName = "SOFTWARE\Server Monitor",
sValueName = "API")
if api == None:
raise Exception
else:
pass
except:
exit()
while 1 == 1:
with open("C:/test.txt", "wb") as b:
computer = wmi.WMI(computer="exsan100")
for disk in computer.Win32_LogicalDisk (DriveType=3):
name = disk.caption
size = round(float(disk.Size)/1073741824, 2)
free = round(float(disk.FreeSpace)/1073741824, 2)
used = round(float(size), 2) - round(float(free), 2)
for mem in computer.Win32_OperatingSystem():
a_mem = (int(mem.FreePhysicalMemory)/1024)
for me in computer.Win32_ComputerSystem():
t_mem = (int(me.TotalPhysicalMemory)/1048576)
u_mem = t_mem - a_mem
for cpu in computer.Win32_Processor():
load = cpu.LoadPercentage
print >>b, api
print >>b, name
print >>b, size
print >>b, used
print >>b, t_mem
print >>b, u_mem
print >>b, load
b.close()
date_list = []
stamp = time.strftime("%c",time.localtime(time.time()))
date_list.append(stamp)
name = re.sub(r"[^\w\s]", "",date_list[0])
os.rename("C:/test.txt", ("C:/%s.txt" % name))
try:
sleep(60.00)
except:
exit()
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(SrvMonSvc)
Have you progressed from your original problem. I had similar problem with a python service and found out that it was missing DLLs since the 'System Path' (not the user path) was not complete.
Running pythonservice.exe with -debug from the command prompt was not a problem because it used correct PATH environment variable, but if your service is installed as a System service it's worth checking out if the System Path variable has all the paths for the required DLLs (MSVC, Python, System32). For me it was missing the python DLLs path, after that it worked again.

Resources