[英]Why does this python script only fail when run from the command line?
I have a small python project that runs on a raspberry pi. 我有一个在树莓派上运行的小python项目。 It monitors temperatures, checks and sends emails, and controls a PDU. 它监视温度,检查并发送电子邮件,并控制PDU。 It runs perfectly from the Thonny IDE included in raspbian. 它可以从raspbian中包含的Thonny IDE完美运行。 However when I run it from the command line, or ideally on startup, it fails in one specific section of code dealing with checking emails. 但是,当我从命令行或理想情况下在启动时运行它时,它在处理电子邮件检查的代码的特定部分中失败。
I installed the email module on the system using pip install. 我使用pip install在系统上安装了电子邮件模块。 Then I realized this was standard in python so i uninstalled it. 然后我意识到这是python中的标准配置,因此我将其卸载了。
This is the error code. 这是错误代码。
Traceback (most recent call last):
File "/home/pi/Documents/Python Files/Temp_Monitor_Project/temp_controller.py", line 122, in <module>
main()
File "/home/pi/Documents/Python Files/Temp_Monitor_Project/temp_controller.py", line 104, in main
check_email_com(state_and_monitoring)
File "/home/pi/Documents/Python Files/Temp_Monitor_Project/temp_controller.py", line 16, in check_email_com
command = check_email.check_for_commands()
File "/home/pi/Documents/Python Files/Temp_Monitor_Project/check_email.py", line 43, in check_for_commands
command = message.checkMail()
File "/home/pi/Documents/Python Files/Temp_Monitor_Project/check_email.py", line 20, in checkMail
email_msg = email.message_from_bytes(data[0][1])
AttributeError: 'module' object has no attribute 'message_from_bytes'
Here is the script it fails in. 这是它失败的脚本。
import imaplib, struct, time, email, Send_Email
#global sender
class Mail():
def __init__(self):
self.user= 'email address'
self.password= 'password'
self.M = imaplib.IMAP4_SSL('imap.gmail.com', '993')
try:
self.M.login(self.user, self.password)
except:
print("mail login failed")
def checkMail(self):
self.M.select()
self.unRead = self.M.search(None, '(SUBJECT "Temp Monitor Command" UnSeen)')
if len(self.unRead[1][0].split()) > 0:
status, data = self.M.fetch(self.unRead[1][0], '(RFC822)')
email_msg = email.message_from_bytes(data[0][1])
if email_msg.is_multipart():
for part in email_msg.walk():
if part.get_content_type() == "text/plain":
body = part.get_payload(decode=True)
body = body.decode()
elif part.get_content_type() == "text/html":
continue
#print(self.M.fetch(self.unRead[1][0], "(BODY[HEADER.FIELDS (FROM)])"))
return body
else:
return -1
I think the problem is nearby environment where you try to execute your code. 我认为问题是您尝试执行代码的附近环境。 Try to check installed modules in both cases. 两种情况下都尝试检查已安装的模块。 You can read here about How to list of used modules during execution. 您可以在此处阅读有关如何在执行期间列出已用模块的信息。 Also you should check which python instance used in both cases. 另外,您还应该检查在两种情况下都使用哪个python实例。 To do this you can execute this 为此,您可以执行此操作
import sys
print(sys.executable)
print(sys.version)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.