2013年8月29日 星期四

[Python] module & class

最近寫python遇到很笨的問題

$ vi serial.py
import serial
                                                  
ser = serial.Serial('/dev/ttyUSB0', 9600)
ser.write("hello world!")
錯誤訊息
Traceback (most recent call last):
  File "serial.py", line 1, in 
    import serial
  File "/home/user/python/serial.py", line 4, in 
    ser = serial.Serial('/dev/ttyUSB0', 9600)
AttributeError: 'module' object has no attribute 'Serial'
如果照stackoverflow的講法, 應該改為from serial import serial
#import serial                                                                   
from serial import serial

ser = serial.Serial('/dev/ttyUSB0', 9600)
ser.write("hello world!")
錯誤訊息
Traceback (most recent call last):
  File "serial.py", line 2, in 
    from serial import serial
  File "/home/user/python/serial.py", line 2, in 
    from serial import serial
ImportError: cannot import name serial
又有人說, 應該改為from serial import *
#import serial                                                                   
#from serial import serial
from serial import *

ser = serial.Serial('/dev/ttyUSB0', 9600)
ser.write("hello world!")
錯誤訊息
Traceback (most recent call last):
  File "serial.py", line 2, in 
    from serial import serial
  File "/home/user/python/serial.py", line 2, in 
    from serial import serial
ImportError: cannot import name serial
最後把檔名serial.py改掉, 隨便改成foo.py就可以了
import serial
                                                  
ser = serial.Serial('/dev/ttyUSB0', 9600)
ser.write("hello world!")
如果再改成
#import serial                                                                   
from serial import serial

ser = serial.Serial('/dev/ttyUSB0', 9600)
ser.write("hello world!")
錯誤訊息
Traceback (most recent call last):
  File "s.py", line 2, in 
    from serial import serial
ImportError: cannot import name serial
如果改回
#import serial
#from serial import serial
from serial import *

ser = serial.Serial('/dev/ttyUSB0', 9600)                                       
ser.write("hello world!")
錯誤訊息
Traceback (most recent call last):
  File "s.py", line 4, in 
    ser = serial.Serial('/dev/ttyUSB0', 9600)
NameError: name 'serial' is not defined
好吧, 我還沒搞懂python的語法就在亂搞了...

沒有留言: