'module' object has no attribute 'Serial' - python

I'm using the following code to communicate my pc with an arduino, but I get the error mentioned in the title, module objet has no attribute Serial.
#!/usr/bin/python
# Importamos la libreira de PySerial
import serial
# Abrimos el puerto del arduino a 9600
PuertoSerie = serial.Serial('/dev/ttyACM0', 9600)
# Creamos un buble sin fin
while True:
# leemos hasta que encontarmos el final de linea
sArduino = PuertoSerie.readline()
# Mostramos el valor leido y eliminamos el salto de linea del final
print "Valor Arduino: " + sArduino.rstrip('\n')
The curios thing is the the code used to work, but then I installed matplotlib and drawnow libraries, I believe that has caused the problem but I don't know how to fix it, because and need those libraries any way.
The other matter is that is I copy the code line to line into the terminal it works but of course I need I with the loop in a .py file.

The solution is to not name the source file serial.py since in such case Python takes that instead of the actually desired serial module.
(Since the question was solved in the comments and no answer has been posted, inspired by a relevant meta question I'm adding this answer to make the question complete. I'm not trying to get credit for deets' solution and I'm posting it as a community wiki answer.)

Related

Unexpected closure of Python program while using ReadProcessMemory from kernel32

I have a really weird behavior from my python program and I need your help to understand where to search.
I made quite a big a program using rpm (ReadProcessMemory from kernel32 windows DLL).
My issue is that my program sometimes closes without any Traceback nor Error.
It does not go to the end and just stops running.
Let's show a simple piece of code :
rPM =ctypes.WinDLL('kernel32',use_last_error=True).ReadProcessMemory
rPM.argtypes = [wintypes.HANDLE,wintypes.LPCVOID,wintypes.LPVOID,ctypes.c_size_t,ctypes.POINTER(ctypes.c_size_t)]
rPM.restype = BOOL
def ReadMemory(self, pPath):
pPath = int.from_bytes(pPath,"little")
PathBuffer = ctypes.create_string_buffer(40)
bytes_read = ctypes.c_size_t()
if not rPM(self.handle,pPath,PathBuffer,40, bytes_read ):
Logger.error("Cannot read Path from memory")
return None
DynamicX=struct.unpack("H", PathBuffer[0x02:0x02 + 2])[0]
DynamicY=struct.unpack("H", PathBuffer[0x06:0x06 + 2])[0]
StaticX=struct.unpack("H", PathBuffer[0x10:0x10 + 2])[0]
StaticY=struct.unpack("H", PathBuffer[0x14:0x14 + 2])[0]
return DynamicX, DynamicY, StaticX, StaticY
for i in range(50):
Logger.debug("Read Info")
ReadMemory()
Logger.debug("Finished Read Info")
Logger.debug("End of program")
Sometimes it will stop at occurence #30, sometime # 45, etc...
and sometimes it comes without any error at all and goes to the end, when running a failing program again it goes through this loop and fail in another one.
The memory I'm reading is the same between two different executions.
How could I get the reason for the closure ? I tried try: except: but never entering into the except catcher.
I'm using python 3.9.1 in windows.
Do you have a hint please, I really don't understand why and cannot fix it :(
Thanks !
Edit :
After more invetigation the crash is not always on rpm function, sometimes it's when using struct.unpack and sometimes (even stranger !) it's during the return statment !
I found on windows error logs a lot of APPCRASH :
Signature du problème
Nom d’événement du problème : APPCRASH
Nom de l’application: python.exe
Version de l’application: 3.7.6150.1013
Horodatage de l’application: 5dfac7ba
Nom du module défaillant: python37.dll
Version du module défaillant: 3.7.6150.1013
Horodateur du module défaillant: 5dfac78b
Code de l’exception: c0000005
Décalage de l’exception: 000000000004d547
Version du système: 10.0.19042.2.0.0.768.101
Identificateur de paramètres régionaux: 1036
Information supplémentaire n° 1: c75e
Information supplémentaire n° 2: c75e78fc0ea847c06758a77801e05e29
Information supplémentaire n° 3: 2730
Information supplémentaire n° 4: 27303d8be681197ea114e04ad6924f93
But I still don't know why it's crashing, I checked the memory and CPU usage of my computer and does not go higher than 60%.
I tried (as you can see) also to change my python version to another one.
Thanks, finally found the issue !
First step was to add :
faulthandler.enable()
It enables the windows crash event to be catched and display in std.err or a file.
It has given me the same thing as #Mark Tolonen said. Read access violation !
After knowing that I double checked my ReadMemory and the buffer size was bigger than expected. It means sometimes I tried to read more than the process memory and tried to read "somewhere else" : Eureka !
Thanks for your tips Mark, I learnt a lot with this one !

What am I doing wrong to generate proper logon message?

I'm pretty new in quickfix, I've tried to read a lot and learn as much as I've could. But I'm facing a weird problem which I've could fix but I cannot understand why it's not working as expected.
First, my venue requires username and password, so I add both to 35=A message. This is expected, what it's not expected it's having field 141 automatically set in logon message, even when in cfg file this is not included, or at least not on purpose. And similar to SenderSubID, TargetCompID and TargetSubID which are required to my venue and having included them in config file are not considered in automatically generated Logon. What I'm doing in a wrong way? Maybe I'm using an incorrect AppDataDictionary, maybe I should change it to customize? Not sure how to fix this in a more smart way instead of using toAdmin to customize a lot of message fields which should be properly generated before.
Code snippet to fix the problem I'm facing
def toAdmin(self, message, sessionID):
# Hook que corre antes de enviar un mensaje al servidor fix
msg_type = fix.MsgType()
message.getHeader().getField(msg_type)
if msg_type.getString() is fix.MsgType_Logon:
message.removeField(141)
message.getHeader().setField(fix.StringField(34, "1"))
message.getHeader().setField(fix.SenderSubID("351"))
message.getHeader().setField(fix.StringField(1408, "T5.0"))
message.getHeader().setField(fix.TargetCompID("XXX"))
message.getHeader().setField(fix.TargetSubID("M3"))
message.setField(fix.Username("xxxxxxx"))
message.setField(fix.Password("xxxxxxx"))
This is my configuration file
[SESSION]
StartTime=00:00:00
SenderCompID=A899
SenderSubID=351
EndTime=00:00:00
ConnectionType=initiator
ApplVerID=9
BeginString=FIXT.1.1
DefaultApplVerID=9
TransportDataDictionary=FIXT11.xml
AppDataDictionary=FIXT11.xml
TargetCompID=XXX
TargetSubID=M3
SocketConnectPort=xxxx
SocketConnectHost=xx.xx.xx.xx
SocketUseSSL=Y
SSLEnable=Y
HeartBtInt=20
ReconnectInterval=30
ResetOnLogout=Y
ResetOnDisconnect=Y
SSLValidateCertificates=Y
ResetSeqNumFlag=N
Thanks a lot for your help, any idea would be welcome.
Regards
I think appart of removing ResetOn... not much more can be done. I've researched for same request in other languages (c#, Java and c) and proposal solution is always which I did. So I assume this is the best approach :(
Thanks a lot for your time and help.

how to use INPUT_PULLUP using pyfirmata2

In Arduino IDE (C++ programming language) we can use pinMode(button, INPUT_PULLUP) to avoid using resistor, but here I'm using Arduino microcontroller and running StandardFirmata inside it, then I use python and pyfirmata library but I don't know how to call INPUT_PULLUP, and if I run the program the output will be true and false.
from pyfirmata2 import Arduino, util
import time
board = Arduino('COM6')
iterator = util.Iterator(board)
iterator.start()
button = board.get_pin('d:2:i')
while True:
print(button.read())
time.sleep(1)
I don't believe that pyfirmata supports pullup. You can try Telemetrix Telemetrix is similar to Firmata, but does not use 7bit bytes. You can view its API here. If you really need to use Firmata, then also look at pymata4.

Debugging with Numba

My first question here, tell me if I am doing things wrong.
My problem
I am writing a module using Numba. Of course I have run accross a segfault, and I can't find where it comes from. So I am trying to debug it using gdb from Numba, but it does not work: the segfault is raised but I get no information from where it comes from:
[Reading symbols]
28 ../sysdeps/unix/sysv/linux/nanosleep.c: Aucun fichier ou dossier de ce type.
0x00007feacc67ea30 in __GI___nanosleep (requested_time=0x7ffdfe227510,
remaining=0x7ffdfe227510) at ../sysdeps/unix/sysv/linux/nanosleep.c:28
Breakpoint 1 at 0x7fea9d234150: file numba/_helperlib.c, line 1131.
Continuing.
double free or corruption (!prev)
51 ../sysdeps/unix/sysv/linux/raise.c: Aucun fichier ou dossier de ce type.
Program received signal SIGABRT, Aborted.
__GI_raise (sig=sig#entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51
(gdb)
During the gdb initialisation, this is also printed in stderr:
attach: No such file or directory.
Note that I have already managed the ptrace problem mentioned here by setting kernel.yama.ptrace_scope=0
Reproducing Numba's debug example
I don't know if it counts as a working reproducer, but I tried to run the example from the Numba documentation that I mentionned earlier :
from numba import njit, gdb_init
import numpy as np
#njit(debug=True)
def foo(a, index):
gdb_init() # instruct Numba to attach gdb at this location, but not to pause execution
b = a + 1
c = a * 2.34
d = c[index] # access an address that is a) invalid b) out of the page
print(a, b, c, d)
bad_index = int(1e9) # this index is invalid
z = np.arange(10)
r = foo(z, bad_index)
print(r)
And I can't get the same output as they do:
[Reading symbols]
0x00007efcb5a60a30 in __GI___nanosleep (requested_time=0x7ffff4990f70,
remaining=0x7ffff4990f70) at ../sysdeps/unix/sysv/linux/nanosleep.c:28
28 ../sysdeps/unix/sysv/linux/nanosleep.c: Aucun fichier ou dossier de ce type.
Breakpoint 1 at 0x7efcabf3d150: file numba/_helperlib.c, line 1131.
Continuing.
Traceback (most recent call last):
File "/home/.../test_segfault.py", line 16, in <module>
r = foo(z, bad_index)
IndexError: index is out of bounds
[Inferior 1 (process 4299) exited with code 01]
My error message does not indicate me the exact line of the segfault, just the jitted function..
And again, I have this message, which may be the source of my problem..
attach: No such file or directory.
Could anyone help me make this work ?
Or a link to an equivalent question ? I have found the documentation and forums really short when it comes to debugging Numba.
Or maybe alternative ways to trace a segfault in Numba jitted functions ?
Thank you for reading me, I hope it is understandable.
the segfault is raised but I get no information from where it comes from
This is not segfault, this is SIGABRT because of double free or corruption that was detected by glibc. This kind of error is better debugged by Valgrind or AddressSanitizer, not gdb. If your program is relatively small use Valgrind because it is easier to use. If not I'd suggest to use AddressSanitizer.

Segmentation fault (core dumped) with cElementTree on ubuntu

I am parsing xml files on a linux ubuntu machine using a python script and the cElementTree package. After a while (at the same point every time) it results in the error
Segmentation fault (core dumped)
This seems to be a C error and hence I think its connected to the C-library I am using (cElementTree). However, I am a bit stuck in how to debug this. If I run the same program on my local Macbook, it works fine without any problem. Only on the linux server does it crash?
How can I debug this? Does anybody know about problems of cElementTree in linux?
Here is my code
import xml.etree.cElementTree as ET
def fill_pubmed_papers_table(list_of_files):
for f in list_of_files:
print "read file %s" % f
inF = gzip.open(f, 'rb')
tree = ET.parse(inF)
inF.close()
root = tree.getroot()
papers = root.findall('PubmedArticle')
root.clear()
for i, citation in enumerate(papers):
write_to_db(citation)
return
the parsing script write_to_db() is fairly long, but I can make it available if anybody is interested.
ok not sure whether it will help anyone, but I found the cause of the set fault. It was not actually connected to cElementTree, but connected to the file read in. I do not completely understand why this happened, but my code works fine if I delete the papers list at the end of the loop meaning I changed the code to
def fill_pubmed_papers_table(list_of_files):
for i, f in enumerate(list_of_files):
print "read file %d names %s" % (i, f)
inF = gzip.open(f, 'rb')
tree = ET.parse(inF)
inF.close()
root = tree.getroot()
papers = root.findall('PubmedArticle')
print "number of papers = ", len(papers)
# we don't need anything from root anymore
root.clear()
for citation in papers:
write_to_db(citation)
# If I do not release memory here I get segfault on the linux server
del papers
gc.collect()
return
I also added the garbage collector just in case, but its not actually needed... deleting the papers list is what solved the problem... I guess it has to do with memory(?)

Categories

Resources