Python Serial works in shell but not script? - python

I'm trying out an example on Arduino: http://playground.arduino.cc/Interfacing/Python
The example (running on Ubuntu) works great in the shell:
import serial
ser = serial.Serial('/dev/ttyACM0', 9600)
while True:
print(ser.readline())
However attempting to execute as a script:
Desktop/python_arduino/./serial.py...
Which executes this:
#!/usr/bin/env python
import serial
ser = serial.Serial('/dev/ttyACM0', 9600)
while True:
print(ser.readline())
And I get this:
Traceback (most recent call last):
File "Desktop/python_arduino/./serial.py", line 2, in <module>
import serial
File "/home/leo/Desktop/python_arduino/serial.py", line 4, in <module>
ser = serial.Serial('/dev/ttyACM0', 9600)
AttributeError: 'module' object has no attribute 'Serial'
What is causing this inconsistency? It should be easy to import serial regardless of shell or script right?

I FOUND IT!
The issue was actually subtle yet simple.
The script filename was the same name as the import.
So the filename was serial.py. The module is called serial, so it created a conflict.
I changed the script's filename, and it worked.

The difference between the shell and your script may be different path setups. Compare the paths and see if anything differs for the script vs. the shell
import ser
print ser.__file__
import sys
print sys.executable

Related

Python 3 script crash on lru_cache

I have raspberry pi acting as MFRC522 card reader. So far I have a script which worked on python 2.7, but when I tried to move to python 3, bizarre thing happened.
I used updated library for it: https://github.com/pimylifeup/MFRC522-python and adjusted my script accordingly
I installed pip3 and spidev
Here is where strange thing happens. If I run demo script from repo above in new folder it works, cool.
But if I put my previous script in the same folder it returns error as below. And after that if I try again to run demo script, same error occurs.
Moving both script to different folder, has the same effect. I can run demo only before my script. Doing that after, is impossible.
Error:
File "/usr/lib/python3.7/re.py", line 297, in <module>
#functools.lru_cache(_MAXCACHE)
AttributeError: module 'functools' has no attribute 'lru_cache'
My script:
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522
import time
import requests
import signal
import sys
import os
# some functions non related to MFRC522
reader = SimpleMFRC522()
while continue_reading:
try:
id, text = reader.read()
#print id
#print "---"
ver = query_server(id)
if ver == 1:
open_relay(5)
else:
#do something
finally:
time.sleep(0.5)
It's like folder is somehow tainted after firing my script, what am I missing?

I get SystemError: Parent module '' not loaded, cannot perform relative import Error when I run my Python Script

My ipmi_server.py file is bellow:
#!/usr/bin/python3
#-*- coding:utf-8 -*-
# Author: dele
import socket
from .ipmi_util import ipmi_handler
from .allowed_ip import allowed_ip_list
HOST = '4.24.124.29'
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
while True:
conn, addr = s.accept()
with conn:
print('Connected by', addr)
if addr and addr[0] not in allowed_ip_list:
conn.sendall('invalid ip')
else:
while True:
data = conn.recv(1024)
if not data:
break
when I run the ipmi_server.py file, there get bellow error:
dele-MBP:ipmi_management ldl$ python3 ipmi_server.py
Traceback (most recent call last):
File "ipmi_server.py", line 7, in <module>
from .ipmi_util import ipmi_handler
SystemError: Parent module '' not loaded, cannot perform relative import
the directory tree is bellow:
I have checked the post, but did not found the solution.
--
EDIT-01
I tried the
from ipmi_management.ipmi_util import ipmi_handler
but get bellow error:
dele-MBP:ipmi_management ldl$ python3 ipmi_server.py
Traceback (most recent call last):
File "ipmi_server.py", line 7, in <module>
from ipmi_management.ipmi_util import ipmi_handler
ImportError: No module named 'ipmi_management'
You cannot use relative imports if you run the ipmi_server directly.
The reason for this is that the relative imports are used relatively to the __name__ of the current file.
Referring to the official python docs
A module’s __name__ is set equal to __main__ when read from standard input, a script, or from an interactive prompt.
You were running the module as a script thus relative imports will not work.
You can run this as a package from the root folder of your project (notice this is executed as a package, thus I've omitted the .py extension)
python -m ipmi_management.ipmi_server
Or alternatively replace the relative imports by absolute imports as documented here:
from ipmi_management.ipmi_util import ipmi_handler
Edit -01
Well as explained well in this answer this would work only if you would import the script interactively.
When executing the script from commandline the sys.path[0] will be equal to the path of the directory that contains the module that you are executing.
Even running the module from the project root likewise: python ipmi_management/ipmi_server.py will make no difference.
For example if your module was located at:
/home/user/projects/qiyun_ipmi_management/ipmi_management/ipmi_server.py', sys.path[0] would be equal to/home/user/projects/qiyun_ipmi_management/ipmi_management/'
The way python imports work, as documented here, the interpreter will simply have no clue where to find the ipmi_management package.
While the first option I suggested still holds, running a module from within a package is not recommended, you should adapt your project to allow for the ipmi_management to be used as package:
Change the ipmi_server.py code as the following:
def run_server():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
while True:
conn, addr = s.accept()
with conn:
print('Connected by', addr)
if addr and addr[0] not in allowed_ip_list:
conn.sendall('invalid ip')
else:
while True:
data = conn.recv(1024)
if not data:
break
add a __main__.py module to your ipmi_management package which then makes use of the ipmi_server.py code like so:
from ipmi_management.ipmi_server import run_server
def main():
run_server()
if __name__ == '__main__':
main()
And by running python -m ipmi_management from the project root will result in the ipmi_server.py being called and the server being run.
Note that I still used absolute imports as they are recommended by PEP-8
Absolute imports are recommended, as they are usually more readable and tend to be better behaved (or at least give better error messages) if the import system is incorrectly configured (such as when a directory inside a package ends up on sys.path):
If you really wish to run the ipmi_server.py module directly, you could use insert the parent directory of that module to sys.path but this is considered unpythonic and generally a bad habit as it makes the python importing system even more obscure.

ImportError: cannot import name 'XBee'

I want to receive data form an Xbee to an other Xbee which is connect to my pc (windows 10). But i can't import the xbee library needed. I install the librairy with :
pip install xbee
Here is my code :
import serial
from xbee import XBee
serial_port = serial.Serial('COM4', 9600)
xbee2 = XBee(serial_port)
while True:
try:
reponse = xbee2.wait_read_frame()
print (reponse)
except KeyboardInterrupt:
break
serial_port.close()
I took the code from : https://python-xbee.readthedocs.io/en/latest/
Here is the error:
Traceback (most recent call last):
File "C:\Users\mis\Desktop\xbee.py", line 2, in <module>
from xbee import XBee
File "C:\Users\mis\Desktop\xbee.py", line 2, in <module>
from xbee import XBee
ImportError: cannot import name 'XBee'
Could somebody help me,
Thanks in advance
I think this is a simple one; looking at your error, it seems that the script you're working on is called xbee.py.
The library you're trying to import is also called xbee.
So, Python is getting a bit confused, it's trying to import XBee from the script you're working in I suspect (I think the module searching mechanism looks in the local folder first).
If you rename your script from xbee.py to something else test_xbee.py for example, you should be fine.

Python type error while embedding

I am trying to run following python code from c++(embedding python).
import sys
import os
import time
import win32com.client
from com.dtmilano.android.viewclient import ViewClient
import re
import pythoncom
import thread
os.popen('adb devices')
CANalyzer = None
measurement = None
def can_start(config_path):
global CANalyzer,measurement
CANalyzer = win32com.client.Dispatch('CANalyzer.Application')
CANalyzer.Visible = 1
measurement = CANalyzer.Measurement
CANalyzer.Open(config_path)
measurement.Start()
com_marshall_stream = pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,CANalyzer)
return com_marshall_stream
When i try to call can_start function, i am getting python type error . Error traceback is mentioned below.
"type 'exceptions.TypeError'. an integer is required. traceback object at 0x039A198"
The function is executing if i directly ran it from the python and also it is executing in my pc, where the code was developed. But later when i transferred to another laptop, i am experiencing this problem.

Curses returning AttributeError: 'module' object has no attribute 'initscr'

I am following the Curses programming HowTo on the Python site, but I am running into a rather bizarre issue.
My code is currently very short, doesn't actually do anything because of this error, I haven't been able to move on. Here's my code:
import curses
#from curses import wrapper
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(True)
def main(stdscr):
begin_x = 20; begin_y = 7
height = 5; width = 40
win = curses.newwin(height, width, begin_y, begin_x)
stdscr.refresh()
stdscr.getkey()
if __name__ == '__main__':
wrapper(main)
and the Traceback:
Traceback (most recent call last):
File "curses.py", line 1, in <module>
import curses
File "/home/nate/Documents/Programming/Python/curses.py", line 4, in <module>
stdscr = curses.initscr()
AttributeError: 'module' object has no attribute 'initscr'
I commented out the from curses import wrapper because that was giving me another error,
Traceback (most recent call last):
File "curses.py", line 1, in <module>
import curses
File "/home/nate/Documents/Programming/Python/curses.py", line 2, in <module>
from curses import wrapper
ImportError: cannot import name wrapper
but I suppose that would be another question.
I am following the tutorial word for word right now, to learn curses, but currently the only thing it's making me do is use curses directed at Python :P.
I am running Python 3.3.2 on Ubuntu 13.10, so this question has nothing to do with this, as he was using Windows and I am not (thankfully :D)
Why am I not able to do this? I'm copying it directly from the Python site, so you'd think it would work!
You named your file curses.py, so Python thinks that file is the curses module. Name it something else.
mv curses.py someOtherName.py
If you get the same error, try removing any .pyc files.
In this case it would be rm curses.pyc.

Categories

Resources