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.
Related
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?
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.
I am trying to run this app:
https://github.com/bmjr/guhTrends
I have python 2.7.x running the following script at command line. I reckon it was written using python3.x. What is deprecated in the code below?
import urllib
import json
import matplotlib.pyplot as plt
dates = urllib.request.urlopen('http://charts.spotify.com/api/tracks/most_streamed/global/weekly/')
dataDates = json.loads(dates.read().decode())
the error:
Traceback (most recent call last):
File "DataMining.py", line 6, in <module>
dates = urllib.request.urlopen('http://charts.spotify.com/api/tracks/most_streamed/global/weekly/')
AttributeError: 'module' object has no attribute 'request'
That script won't work under python2 as urllib of python2 has no request module.
Use urllib2.urlopen instead of urllib.request if you want start running that script under python2 .
To get python script work on bith (python2 and python3) use six module which is Python 2 and 3 Compatibility Library.
from six.moves import urllib
import json
import matplotlib.pyplot as plt
dates = urllib.request.urlopen('http://charts.spotify.com/api/tracks/most_streamed/global/weekly/')
dataDates = json.loads(dates.read().decode())
You're requesting a resource that is not currently available (I'm seeing a 504). Since this could potentially happen any time you request a remote service, always check the status code on the response; it's not that your code is necessarily wrong, in this case it's that you're assuming the response is valid JSON without checking whether the request was successful.
Check the urllib documentation to see how to do this (or, preferably, follow the recommendation at the top of that page and use the requests package instead).
I just write this code in Python under Raspbian OS:
import smtplib
from = '****#hotmail.de'
to = '****#hotmail.de'
msg = 'Testmail'
usr = '****#hotmail.de'
psw = '****'
server = smtplib.SMTP('smtp.live.de',25)
server.login (usr,psw)
server.sendmail (from, to, msg)
server.quit()
And get following Error-Message:
Traceback (most recent call last):
File "ail.py", line 1, in <module>
import smtplib
File "/usr/lib/python2.7/smtplib.py", line 46, in <module>
import email.utils
File "/home/pi/email.py", line 6, in <module>
smtp =smtplib.SMTP('smtp.live.com',25)
AttributeError: 'module' object has no attribute 'SMTP'
What is my fault? Could somebody help me - please?
Regards
Your problem is that you named your script email.py, or maybe an earlier version of it. That means that it shadows the standard-library email module/package. So, when smtplib tries to import email or import email.utils, it gets your code instead of the stdlib code it wants.
The solution is to rename your script to not match any of the stdlib modules and packages (or at least not any of the ones you're directly or indirectly using).
If you've already renamed it to ail.py (as the traceback seems to suggest) and it's still causing problems, make sure to delete your original email.py, and any .pyc/.pyo files of the same name. As long as they're in the current working directory (or elsewhere on sys.path), they can still interfere with the stdlib.
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