0

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:

  1. changing file name from 'serial.py' to 'any_other_name.py' and vise versa
  2. deleting related .pyc file
  3. Installing 'pip install pyserial'
  4. 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

1 Answer 1

1

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 :)
Sign up to request clarification or add additional context in comments.

3 Comments

When I tried to run the first code: error is coming: 'ModuleNotFoundError: No module named 'serial''.. in help (serial) it is showing me 'NameError: name 'serial' is not defined' .. Does any one is having Idea to solve this issue?
I have solve the problem. I am using python anaconda spyder and for that, I needed to install 'conda install pyserial' not 'pip install pyserial'.
so you were using 2 different installation of python, that's why sometimes it found serial sometimes not ;) glad to hear you found the root cause

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.