Python CanOpen canGetNumberOfChannels not defined | kvaser canlib is unavailable - python

i tried to run my Python Program on my Linux maschine but when i try to run it it is having a hard time finding all the nessasary modules needed for it to work.
i installed CanOpen to my project
import threading
import sys
sys.path.append('venv/Lib/site-packages')
sys.path.append('venv/Lib/site-packages/can/interfaces/kvaser')
sys.path.append('/test/Python39/Lib')
import canopen
from canopen.network import MessageListener, NodeScanner
from canopen.nmt import NmtMaster
from canopen.sync import SyncProducer
from canopen.timestamp import TimeProducer
if __name__ == '__main__':
network = canopen.Network()
network.connect(bustype='kvaser', channel=0, bitrate=250000)
it is showing me following error in the Terminal:
Kvaser canlib is unavailable.
Traceback (most recent call last):
File "/test/Can_T1/main.py", line 60, in <module>
network.connect(bustype='kvaser', channel=0, bitrate=250000)
File "/test/Can_T1/venv/Lib/site-packages/canopen/network.py", line 112, in connect
self.bus = can.interface.Bus(*args, **kwargs)
File "/test/Can_T1/venv/Lib/site-packages/can/interface.py", line 120, in __new__
bus = cls(channel, *args, **kwargs)
File "/test/Can_T1/venv/Lib/site-packages/can/interfaces/kvaser/canlib.py", line 437, in __init__
canGetNumberOfChannels(ctypes.byref(num_channels))
NameError: name 'canGetNumberOfChannels' is not defined
Is there any way to define 'canGetNumberOfChannels'?

You have to install the canlib on your machine as well. Right now, you just have installed the SDK. If you are running on linux you have to install libcanlib.so on your machine. Take a look at the part that is related to your operating system on this link: https://pypi.org/project/canlib/

Related

Impossible to retrieve data form pyattck module

I am using the pyattck module to retrieve information from mitre att&ck.
Versions:
- pyattck==7.0.0
- pyattck-data==2.5.2
Then, I just created a simple main.py file to test the module.
from pyattck import Attck
def main():
attck = Attck()
for technique in attck.enterprise.techniques:
print(technique.name)
if __name__ == '__main__':
main()
When running the main.py script I get the following exception:
Traceback (most recent call last):
File "/<path>/main.py", line 15, in <module>
main()
File "/<path>/main.py", line 8, in main
for technique in attck.enterprise.techniques:
File "/<path_venv>/lib/python3.10/site-packages/pyattck/attck.py", line 253, in enterprise
from .enterprise import EnterpriseAttck
File "/<path_venv>/lib/python3.10/site-packages/pyattck/enterprise.py", line 7, in <module>
class EnterpriseAttck(Base):
File "/<path_venv>/lib/python3.10/site-packages/pyattck/enterprise.py", line 42, in EnterpriseAttck
__attck = MitreAttck(**Base.config.get_data("enterprise_attck_json"))
File "/<path_venv>/lib/python3.10/site-packages/pyattck_data/attack.py", line 55, in __init__
raise te
File "/<path_venv>/lib/python3.10/site-packages/pyattck_data/attack.py", line 53, in __init__
self.__attrs_init__(**kwargs)
File "<attrs generated init pyattck_data.attack.MitreAttck>", line 14, in __attrs_init__
File "/<path_venv>/lib/python3.10/site-packages/pyattck_data/attack.py", line 66, in __attrs_post_init__
raise te
File "/<path_venv>/lib/python3.10/site-packages/pyattck_data/attack.py", line 62, in __attrs_post_init__
data = TYPE_MAP.get(item['type'])(**item)
TypeError: 'NoneType' object is not callable
Anyone knows where is the issue? Maybe I have forgotten to import something? It would be helpful to know if this module actually works in another version. This one is the lasted stable one ATTOW.
UPDATE
There is am issue with this project. Mitre added some new features that are not supported by the module and make it unusable.
There is an issue on github related to this.
They have already fixed this issue in future releases. You just need to update your package pyattck-data form the bugged version 2.5.2 to 2.6.1 (or any newer).
If you are using pip, just run this:
pip install --upgrade pyattck-data
If you are using conda (inside your venv):
conda update pyattck-data

Unable to use "socket" in my vscode using python

I was just learning socket programming in python and was unable to run my socket commands in vs code.
the code i wrote is:-
import socket
import threading
PORT=5050
SERVER =socket.gethostbyname(socket.gethostname)
print(SERVER)
The code produces this error:
Traceback (most recent call last):
File "c:\Users\Gurkirat Singh\Desktop\tempCodeRunnerFile.py", line 1, in <module>
import socket
File "c:\Users\Gurkirat Singh\Desktop\socket.py", line 3, in <module>
from xmlrpc.client import Server
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\xmlrpc\client.py", line 136, in <module>
import http.client
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\http\client.py",
line 789, in <module>
class HTTPConnection:
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\http\client.py",
line 837, in HTTPConnection
def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
AttributeError: partially initialized module 'socket' has no attribute '_GLOBAL_DEFAULT_TIMEOUT' (most likely due to a circular import)
Looking at your stack trace, you seem to have a file named socket.py:
File "c:\Users\Gurkirat Singh\Desktop\socket.py", line 3, in <module>
from xmlrpc.client import Server
Having a file named socket.py in your workspace causes import problems because Python won't import its library module socket but instead will import your own file.
Rename your file from socket.py to something else like mysock.py and delete anything from your Desktop directory called socket.pyc if it exists.

Python Key-logger (.error.DisplayNameError: Bad display name "")

I was following up on a tutorial to build a python keylogger and ended up with this problem. I have gone over my codes about 10 times and compared it with other sources but yet still getting the same error. I have seen similar complaints while looking for a solution, and I hypothesize that it might be my computer( Mac OSX 10.12 sierra, MacBook Pro (13-inch, Mid 2010)). I am not a computer expert so I am not too sure.
If it is my system architecture, how do I by-pass it ?
if not, what am I missing in the code or where is my error ?
import pyxhook
log_file = "/Users/VemPC/Desktop/log_file.log"
def onPress(event):
fob = open(log_file, 'a')
fob.write(event.key)
fob.write('\n')
if event.key.ascii == 96 :
fob.close()
new_hook.cancel()
new_hook = pyxhook.HookManager()
new_hook.KeyDown = onPress
new_hook.HookKeyboard()
new_hook.start()
Error:
Traceback (most recent call last):
File "key_logger.py", line 15, in <module>
new_hook = pyxhook.HookManager()
File "/Users/VemPC/Desktop/Challenges/venv/lib/python3.7/site-packages/pyxhook/pyxhook.py", line 67, in __init__
self.local_dpy = display.Display()
File "/Users/VemPC/Desktop/Challenges/venv/lib/python3.7/site-packages/Xlib/display.py", line 89, in __init__
self.display = _BaseDisplay(display)
File "/Users/VemPC/Desktop/Challenges/venv/lib/python3.7/site-packages/Xlib/display.py", line 71, in __init__
protocol_display.Display.__init__(self, *args, **keys)
File "/Users/VemPC/Desktop/Challenges/venv/lib/python3.7/site-packages/Xlib/protocol/display.py", line 85, in __init__
name, protocol, host, displayno, screenno = connect.get_display(display)
File "/Users/VemPC/Desktop/Challenges/venv/lib/python3.7/site-packages/Xlib/support/connect.py", line 73, in get_display
return mod.get_display(display)
File "/Users/VemPC/Desktop/Challenges/venv/lib/python3.7/site-packages/Xlib/support/unix_connect.py", line 61, in get_display
raise error.DisplayNameError(display)
Xlib.error.DisplayNameError: Bad display name ""
pyxhook seems to be a linux specific library. Specifically, it is an implementation of PyHook for linux, using X, the window system library. MacOS provides some support for this, but not all, as MacOS is not built on X. It seems like you won't be able to use this library on your system.

matplotlib RuntimeError in cron job before actual import

I have a module I'm writing that uses matplotlib. However, I need it to work with a display(e.g. command-line execution), or when theres no display ( SGE/qsub cluster job, or a cron job).
I found this answer ( Automatic detection of display availability with matplotlib ), which works for the command-line execution and within a cluster job. But, in a cron job, it fails to properly import matplotlib, and seems to throw an exception before I import it.
In the cronjob, I try to import my module with the following script:
import os
os.environ['PYTHONPATH'] = 'path/to/my/module/dir:%s' % os.environ['PYTHONPATH']
print 'now loading mymodule...'
import mymodule
and mymodule.py just has the code from the earlier linked answer:
#!/usr/bin/python
import os
print 'testing import method...'
import matplotlib
r = 0
try :
r = os.system('python -c "import matplotlib.pyplot as plt;plt.figure()"')
except RuntimeError :
pass
print 'r=%d' % r
if r != 0:
print 'matplotlib: running in cluster, using Agg!'
matplotlib.use('Agg')
import matplotlib.pyplot as plt
I get this error message from the cron service:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/afs/ifh.de/user/u/user/.local/lib/python2.6/site-packages/matplotlib/pyplot.py", line 109, in <module>
_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
File "/afs/ifh.de/user/u/user/.local/lib/python2.6/site-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup
globals(),locals(),[backend_name],0)
File "/afs/ifh.de/user/u/user/.local/lib/python2.6/site-packages/matplotlib/backends/backend_gtkagg.py", line 14, in <module>
from matplotlib.backends.backend_gtk import gtk, FigureManagerGTK, FigureCanvasGTK,\
File "/afs/ifh.de/user/u/user/.local/lib/python2.6/site-packages/matplotlib/backends/backend_gtk.py", line 16, in <module>
import gtk; gdk = gtk.gdk
File "/usr/lib64/python2.6/site-packages/gtk-2.0/gtk/__init__.py", line 64, in <module>
_init()
File "/usr/lib64/python2.6/site-packages/gtk-2.0/gtk/__init__.py", line 52, in _init
_gtk.init_check()
RuntimeError: could not open display
now loading mymodule...
testing import method...
r=256
matplotlib: running in cluster, using Agg!
I think its trying and failing to import matplotlib, which is throwing a RuntimeError, before getting to my code in mymodule.py . I can see that it gets to my code and runs it, but the Traceback message makes me nervous.
Why is it loading matplotlib(and crashing) before I tell it to(with Agg)? How can I fix/hide that traceback message?
As a dirty trick to hide the traceback message, just pipe all errors in the cronjob to /dev/null:
script.py 2> /dev/null

Tracing down missing import from py4j on error "trying to call a package"

Given the following python snippet:
from pyspark.mydb.mydb import *
class HBaseTest:
def __init__(self):
from pyspark.context import SparkContext
sc = SparkContext('local[4]', 'PythonTest')
self._hbctx = MyDbSQLContext(sc)
The line of interest is the last one: the MyDbSQLContext is a class in the org.apache.spark.mydb package. There is a python wrapper for it in the pyspark.mydb.mydb.py file
In an attempt to make the imports known to the py4j java gateway, the following statements are executed:
java_import(self._sc._gateway.jvm,'org.apache.spark.sql.mydb.*')
java_import(self._sc._gateway.jvm,'org.apache.hadoop.conf.Configuration')
However on the last line of the original snippet:
self._hbctx = MyDbSQLContext(sc)
We get the following error:
sc=org.apache.spark.SparkContext#4925069a conf=<py4j.java_gateway.JavaMember object at 0x10bdd5090>
Traceback (most recent call last):
File "pyspark/hbase/hbase_tests.py", line 81, in <module>
test._test()
File "pyspark/hbase/hbase_tests.py", line 76, in _test
self.create_test_tables()
File "pyspark/hbase/hbase_tests.py", line 46, in create_test_tables
self._ctx().sql(create_sql).toRdd().collect()
File "/shared/pyjava/python/pyspark/sql.py", line 1620, in sql
return SchemaRDD(self._ssql_ctx.sql(sqlQuery).toJavaSchemaRDD(), self)
File "/shared/pyjava/python/pyspark/hbase/hbase.py", line 58, in _ssql_ctx
self._scala_HBaseSQLContext = self._get_hbase_ctx()
File "/shared/pyjava/python/pyspark/hbase/hbase.py", line 83, in _get_hbase_ctx
return self._jvm.HBaseSQLContext(self._jsc.sc())
File "/shared/pyjava/python/lib/py4j-0.8.2.1-src.zip/py4j/java_gateway.py", line 726, in __getattr__
py4j.protocol.Py4JError: Trying to call a package.
UPDATE I have spent more time analyzing the way that imports are performed for hive. They are added via the spark-submit script that internally invokes compute-classpath.sh. I had already correctly added the $MYDB_HOME/lib/* to the classpath in that script. The mydb jar files are available on the classpath:
In addition, the java_imports are being printed - and here they do show the mydb imports:
java_imports: [u'org.apache.hadoop.conf.Configuration', u'org.apache.spark.SparkConf',
u'org.apache.spark.sql.hive.LocalHiveContext', u'org.apache.spark.sql.hive.TestHiveContext',
u'org.apache.hadoop.mydb.client.Client', u'scala.Tuple2', u'org.apache.spark.sql.mydb.mydbSQLContext',
u'org.apache.spark.sql.hive.HiveContext', u'java.lang', u'org.apache.hadoop.mydb', u'org.apache.hadoop.mydb.client',
u'org.apache.hadoop.mydb.filter', u'org.apache.hadoop.mydb.util', u'org.apache.log4j', u'org.apache.spark.api.java',
u'org.apache.spark.api.python', u'org.apache.spark.mllib.api.python', u'org.apache.spark.sql', u'org.apache.spark.sql.mydb']
It is presently unclear what the source of this issue is. We have verified:
mydb classes are in the path
mydb classes are being imported by java_import
AFAICT the patterns followed for importing and using hive classes are being similarly followed for mydb
I am at a loss what else to examine to track this java class/classpath issue down.

Categories