I am using Python Anaconda 2.7. I would like to toggle the port using serial communication, But I am getting error: AttributeError: 'module' object has no attribute 'Serial'
My sample program is:
import serial
import time
#remember to adjust “COM3”
port = serial.Serial("COM3", 19200, timeout=0.5)
#turn on port 2, sleep 2 seconds, turn off port 2
port.write(b"\nF2\r")
time.sleep(2.0)
port.write(b"\nF2\r")
#turn on port 2 and 7, sleep 2 seconds, turn off port 2 and 7
port.write(b"\nF2\r\nF7\r")
time.sleep(2)
port.write(b"\nF2\r\nF7\r")
#close the port
port.close()
I have tried many solutions:
changing file name from 'serial.py' to 'any_other_name.py' and vise versa
deleting related .pyc file
Installing 'pip install pyserial'
Doing From serial import serial
When I run the same program from psychopy, it is working really fine. I don't know How to solve it. If some one can give me suggestions that It would be great help for me. Thanking you in advance.
Ravi
Your code seems good, so the problem you encounter is probably due to a bad import.
You really should avoid to name your python script like "standard" modules (serial.py, string.py...), because by doing this, you expose yourself to accidentally import those files instead of the correct one (probably what happened to you).
If you need to be sure of what you're importing, try this :
import serial
print serial.__file__ # this will tell you the position of the file you've imported and help you to be sure of what you're using.
# in case you're not importing a module, only a class... try this :
help(serial) # even without any help, it will give you at the end the path where this object is defined :)
Related
So I have been trying to use the ZMQ module to make a publisher subscriber model
I downloaded the library in Pycharm, made sure that it is the latest version.
And when I try to use things like ".setsockopt" it keeps saying "unresolved attribute reference setsockopt for class "Socket" and ask me to add a method to the class "Socket" This is exteremly annoying and I have no idea how to solve this. I went online to read tutorials and all they did is just "import zmq" and everything is fine. Please help me=(
Its not only setsockopt, I have been trying things like .send_pyobj and it doesn't work too!
Here I literally copy and paste a code from youtube: youtube.com/watch?v=-_CXA8SZsOs
please go to time 5:58, I copy that code and my pycharm say that on line15: socket.send_pyobj has error and say the same thing "unresolved attribute reference setsockopt for class "Socket"
Somebody please help me your help means a lot to me
The youtube code:
import zmq
from time import sleep
context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind('tcp://127.0.0.1:2000')
messages = [100,200,300]
curMsg = 0
while(True):
sleep(1)
socket.send_pyobj({curMsg:messages[curMsg]})
if (curMsg == 2):
curMsg = 0
else:
curMsg = curMsg +1
I have the following traceback error incase you are wondering
note that it is for rec_obj which is pretty much the same issue with send_obj and also setsockopt. Basically it is missing for no reasons
File "C:\Users\jacky\PycharmProjects\testing_the_send_data_and_receive_data_thing\venv\lib\site-packa
ges\zmq\sugar\attrsettr.py", line 44, in getattr
raise AttributeError(
AttributeError: Socket has no such option: REC_PYOBJ
I am trying to print to a TM-T20II thermal printer so I can print receipts. Here is my code:
from escpos import printer
from escpos import *
import escpos
from escpos import config
import usb.core
import usb.util
import usb.backend.libusb1
from ctypes import c_void_p, c_int
backend = usb.backend.libusb1.get_backend(find_library=lambda x: "libusb-1.0.dll")
backend.lib.libusb_set_option.argtypes = [c_void_p, c_int]
backend.lib.libusb_set_option(backend.ctx, 1)
p = printer.Usb(0x04b8,0x0e15,0,0x82,0x01, backend=backend)
p.text('test')
I am using a usbdk backend, without it I get a 'NotImplementedError: Operation not supported or unimplemented on this platform.' I'm doing this because for my program to work I need to use the default Epson drivers. When I run this code the error I get is:
<File "C:\Users\maxsl\anaconda3\lib\site-packages\usb\core.py", line
234, in get_interface_and_endpoint
return self._ep_info[endpoint_address]
KeyError: 1
During handling of the above exception, another exception occurred:
File
"C:\Users\maxsl\anaconda3\lib\site-packages\usb\backend\libusb1.py",
line 604, in _check
raise USBError(_strerror(ret), ret, _libusb_errno[ret])
USBError: [Errno None] Other error>
This error only occurs when I add p.text() in. Finding the printer and everything else is no problem. I also want to say that write() works in the PyUSB module, but it would be much more convenient for me to not have to translate the outputs in my program to the confusing ESC/P language.
I am using Spyder 4 with anaconda (python 3.7) 64-bit, libusb 1.0.22b9, most recent pyusb on github (PyPi version got unimplemented error), and python-escpos 3.0a8. I believe they are all 64-bit as well. I have the libusb1.dll from 64x folder in my System32 and the 86x one in SysWoW64 as recommended. I also have Usbdk installed. Please let me know if you have any ideas to fix or if you need more details. Been googling this for like a week.
Isn't it a problem with the printer's USB mode setting?
TM-T20II printer has the modes of USB vender-defined class (COM Port) and USB printer class.
The VID/PID is USB vender-defined class=0x04b8:0x0202 and USB printer class=0x04b8:0x0e15 respectively.
TM-T20II Technical Reference Guide page 89
You should be able to change it with the printer's setting utility.
Alternatively, try changing the PID designation to 0x0202 as is, or try communicating as a COM port instead of a raw USB device.
Or it is possible that the advanced printer driver or Windows print spooler is already using the device and other programs cannot be used.
If the device driver is installed, try uninstalling it.
For anyone else with the same problem as me, what I did was I installed Epson's TM Virtual Port Driver and set the printer to a COM port. I then had to go into the printer's settings and manually change the port to the virtual one. I then altered my code to this:
from escpos import printer
pr = printer.Serial('COM2')
data= '''
hello world
'''
pr.text(data)
pr.close()
And it finally worked! You can see I cut my code down quite a bit. It turns out I don't even need to change the backend. So strange Usb doesn't work but serial does. As long as it works though! Thanks to kunif for the guidance to my solution, never even considered checking the serial ports.
I made a custom library to communicate with my own board. The codes in library work but when i call the library itself i get an error.
I assumed the library is not working, so i put a print function in the library. It seems, that function works and the functions with serial communication are the problem.
I checked the communication code by itself but it works each time. Assuming there are some things to handle when using serial in a custom library, which i dont know any.
iDealibrary.py
import serial
import time
ser=serial.Serial('COM5',9600)
def ConnectIdeaLab():
ser.sendBreak()
a=ser.read()
b=ser.read()
if(a==b'O' and b ==b'K' ):
ser.write(b'b')
ser.write(b'b')
ser.write(b'b')
ser.write(b'a')
ser.write(b'a')
c=ser.read()
if(c==b'!'):
ser.write(bytes([3]))
print("iDeaLab Moduna Girildi!")
time.sleep(0.005)
ser.sendBreak()
#this is the connection function.
def printanything(parametre):
print("writing: ",parametre)
#this is the print function to check if library is working.
example.py
import iDealibrary
iDealibrary.ConnectIdeaLab()
iDealibrary.printanything("selam")
#this does not work
I expect the last code to connect and print iDealab moduna girildi. Instead, i get
raise SerialException("ClearCommError failed ({!r})".format(ctypes.WinError()))
I managed to solve the problem. Mad Physicist is right, the problem is serial port stays open. When i try to re-run the program it tries to open a port which is already open.
After adding a CloseSerial function in my library and calling it on the example, the problem solved.
#File name iDealibrary.py
def CloseSerial():
ser.close()
#File name example.py
iDealibrary.ConnectIdeaLab()
iDealibrary.CloseSerial()
I am trying to learn how to send a list of lists in Python to R -script which runs statistical methods and gives two or three data frames back to Python
I stumbled across the pyRserve package. I was able to follow the manual in their documentation and everything works great in command line (>>> ). When I run a script, it does not stop. I have installed Rserve package and started its service in RStudio. Below is the code:
import pyRserve
print "here1" #prints this line...
conn = pyRserve.connect(host='localhost', port=6311)
print "here2"
a= conn.eval('3+5')
print a
Can anyone please help?
The (docs) suggest:
$ python
>>> import pyRserve
>>> conn = pyRserve.connect()
And then go on with:
To connect to a different location host and port can be specified explicitly:
pyRserve.connect(host='localhost', port=6311)
This is not meant to indicate that both lines should be run. The second line should be viewed as a potential modifier for the first. So if you need an alternate address or port, then it should look like:
$ python
>>> import pyRserve
>>> conn = pyRserve.connect(host='localhost', port=6311)
Also note this caveat for windows users:
Note On some windows versions it might be necessary to always provide ‘localhost’ for connecting to a locally running Rserve instance.
I have found this odd issue where running the following code in a python shell works but running a python file with the code in it does not.
import serial
connection = serial.Serial("/dev/ttyACM0", 19200)
write = connection.write("h\r".encode())
print(connection.read(connection.inWaiting()))
connection.close()
running directly in python3 shell gives the following output (which is correct):
b'halt ack\r\n'
while running a python file gives this output:
b''
I have no idea what is causing the inconsistency, does anyone know? No amount of delay seems to fix the problem.