Physical Gmail Notifier Led - python

So I was trying to make a physical Gmail notifier . Using a 330 ohm resistor and an LED to blink when I have unread mail. This is proving to be tougher then I thought. I keep getting this output when I go to execute the python code.
raspi_gmail.py:34: RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings.
GPIO.setup(PIN_mail, GPIO.OUT)
Traceback (most recent call last):
File "raspi_gmail.py", line 45, in <module>
newmails = int(feedparser.parse("https://" + USERNAME + ":" + PASSWORD + "#mail.google.com/gmail/feed/atom")["feed"]["fullcount"])
File "/usr/local/lib/python2.7/dist-packages/feedparser.py", line 356, in __getitem__
return dict.__getitem__(self, key)
KeyError: 'fullcount'
This is the Code I'm using , with the credentials cut out of course.
from os.path import exists
import RPi.GPIO as GPIO, feedparser
GPIO.setmode(GPIO.BCM)
file=".unreadmail.txt"
# insert your username and password
USERNAME="[USERNAME]#gmail.com"
PASSWORD="[PASSWORD]"
# if .unreadmail.txt doesn't exists the script wont work
# the following lines check if the file exists and create it if needed
if exists(file) == False:
data = open(file, 'w')
data.write("0")
data.close()
# edit these two value depending on your pin wiring
PIN_mail=6
PIN_check=18
data = open(file, 'r')
status=int(data.read())
data.close()
GPIO.setup(PIN_mail, GPIO.OUT)
GPIO.setup(PIN_check, GPIO.OUT)
GPIO.output(PIN_check, False)
if status == 0:
GPIO.output(PIN_mail, True)
else:
GPIO.output(PIN_mail, False)
newmails = int(feedparser.parse("https://" + USERNAME + ":" + PASSWORD + "#mail.google.com/gmail/feed/atom")["feed"]["fullcount"])
# output on .unreadmail.txt and GPIO
data = open(file, 'w')
if newmails > 0:
GPIO.output(PIN_mail, False)
data.write("1")
else:
GPIO.output(PIN_mail, True)
data.write("0")
GPIO.output(PIN_check, True)
data.close()
Any help would be appreciated , I'm kind of a newbie to this whole aspect.

Related

Python code not storing readings in a .csv file. "sequence expected" error recieved. Any idea how to fix this?

I was applying a code that reads the coordinates from a gps and fills it in a .csv file.i am new to all of this so i can't get my head around this problem. I have used the "csv" code in other programs and it has worked. But here it is giving me a hard time. The error is as follows:
Traceback (most recent call last):
File "GPScodetest2.py", line 48, in <module>
data_writer.writerow(data)
_csv.Error: sequence expected
How to fix this?
P.S the code:
from time import sleep, strftime, time
import serial
import pynmea2
import datetime
from csv import writer
#setup the serial port to which gps is connected
port = "/dev/ttyS0"
ser = serial.Serial(port, baudrate = 9600, timeout = 0.5)
dataout = pynmea2.NMEAStreamReader()
counter = 0
def get_sense_data():
while True:
newdata = ser.readline()
if newdata[0:6] == '$GPGGA':
parsed_line = pynmea2.parse(newdata)
latitude_reading = parsed_line.latitude
alpha = latitude_reading
#print(newlat)
longitude_reading = parsed_line.longitude
beta = longitude_reading
#print(newlong)
#print(latitude_reading)
#print(longitude_reading)
sense_data=[]
sense_data.append(counter)
sense_data.append(datetime.datetime.now())
sense_data.append(alpha)
sense_data.append(beta)
return sense_data
with open('GPSdata.csv', 'w+') as f:
data_writer = writer(f)
data_writer.writerow(['Term No.','Date and Time','Latitude',
' Longitude'])
while True:
data = get_sense_data
data_writer.writerow(data)
counter = counter + 1
You aren't calling the function:
data = get_sense_data
Try calling it:
data = get_sense_data()

how i can send more than 2 arguments on telnet session in python?

I have two lists that have user name and password. I want to check which one is correct by iterating through two zipped lists but it isn't working.
Below is the traceback
Traceback (most recent call last):
File "C:\Users\mohamed\Downloads\second_PassWD_Test.py", line 27, in <module>
mme=tn.write(j,i)
TypeError: write() takes exactly 2 arguments (3 given)
Below is the code throwing the exception.
import telnetlib
import re
HOST = "192.168.1.1"
USER = ["admin\n","admin\n","admin"]
PASS = ["cpe#","1234"," "]
try:
tn = telnetlib.Telnet(HOST)
except:
print "Oops! there is a connection error"
frist_log = tn.read_until(":")
if "log" in frist_log:
while 1:
for i,j in zip(USER,PASS):
tn.write(j,i)
break
Telnet.write(buffer) only takes two arguments first is the telnet object and the other is a buffer to send to your session, hence your solution will throw an exception. One way to solve the problem is like a except script using the expect api and use a list of expected output as shown in example below
USER = ["admin\n","admin\n","admin"]
PASS = ["cpe#","1234"," "]
prompt = "#" ## or your system prompt
tn = telnetlib.Telnet(HOST)
first_log = tn.read_until(":")
for user,password in zip(USER,PASS):
try:
tn.write(user)
tn.expect([":"],timeout = 3) # 3 second timeout for password prompt
tn.write(password+"\n")
index,obj,string = tn.expect([":",prompt],timeout = 3)
found = string.find(prompt)
if found >= 0:
break # found the username password match break
###else continue for next user/password match
except:
print "exception",sys.exc_info()[0]

DHT Sensor Python script error

I have a sensor type DHT22 connected to a raspberry.
I have written a script in python but when I run it I get errors
#!/usr/bin/python
import MySQLdb
import subprocess
import re
import sys
import time
import datetime
import Adafruit_DHT
conn = MySQLdb.connect("localhost","zeus","gee3g673r","logi")
while(True):
date = time.strftime("%d/%m/%Y")
clock = time.strftime("%H:%M")
#output = subprocess.check_output(["/usr/bin/AdafruitDHT.py 2302", "4"]);
output = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, 4)
matches = re.search("Temp =\s+([0-9.]+)", output)
if (not matches):
time.sleep(0)
continue
temp = float(matches.group(1))
matches = re.search("Hum =\s+([0-9.]+)", output)
if (not matches):
time.sleep(0)
continue
humidity = float(matches.group(1))
# MYSQL DATA Processing
c = conn.cursor()
c.execute("INSERT INTO data_th (date, clock, temp, hum) VALUES (%s, %s,%s, %s)",(date, clock, temp, humidity))
#print "DB Loaded"
time.sleep(360)
This is the error encountered on running the script:
root#raspberrypi:/home# ./hdt.py
Traceback (most recent call last):
File "./dht.py", line 22, in <module>
matches = re.search("Temp =\s+([0-9.]+)", output)
File "/usr/lib/python2.7/re.py", line 142, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or buffer
Adafruit_DHT.read_retry() does not return string. re.search expects string as second parameter.
Please have a look at code below (taken from Adafruit_Python_DHT/examples):
# Try to grab a sensor reading. Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
# Un-comment the line below to convert the temperature to Fahrenheit.
# temperature = temperature * 9/5.0 + 32
# Note that sometimes you won't get a reading and
# the results will be null (because Linux can't
# guarantee the timing of calls to read the sensor).
# If this happens try again!
if humidity is not None and temperature is not None:
print 'Temp={0:0.1f}* Humidity={1:0.1f}%'.format(temperature, humidity)
else:
print 'Failed to get reading. Try again!'
sys.exit(1)

KeyError: 'fullcount' in mail script

I wrote a Python script to check my email and turn on an LED when I have new mail.
After about 1 hour, I got the error:
Traceback (most recent call last):
File "checkmail.py", line 10, in <module>
B = int(feedparser.parse("https://" + U + ":" + P + "#mail.google.com/gmail/feed/atom")["feed"]["fullcount"])
File "/usr/local/lib/python2.7/dist-packages/feedparser.py", line 375, in __getitem__
return dict.__getitem__(self, key)
KeyError: 'fullcount'
I looked here
and didn't find an answer. Here is my code:
#!/usr/bin/env python
import RPi.GPIO as GPIO, feedparser, time
U = "username"
P = "password"
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
A = 23
GPIO.setup(A, GPIO.OUT)
while True:
B = int(feedparser.parse("https://" + U + ":" + P + "#mail.google.com/gmail/feed/atom")["feed"]["fullcount"])
if B > 0:
GPIO.output(A, True)
else:
GPiO.output(A, False)
time.sleep(60)
I'm running this on a Raspberry Pi.
Thanks in advance for any help.
You need to add some debug code and see what this call returns:
feedparser.parse("https://" + U + ":" + P + "#mail.google.com/gmail/feed/atom")["feed"]
It's clearly something that does not contain a "fullcount" item. You might want to do something like this:
feed = feedparser.parse("https://{}:{}#mail.google.com/gmail/feed/atom".format(U, P))
try:
B = int(feed["feed"]["fullcount"])
except KeyError:
# handle the error
continue # you might want to sleep or put the following code in the else block
That way you can deal with the error (you might want to catch ValueError too, in case int() fails because of an invalid value) without it blowing up your script.

Python win32com open OpenOffice Calc (.xls) spreadsheet through Task Scheduler

I am trying to open an existing .xls document with OpenOffice using the Python 2.7 win32com module. The following script runs perfectly through an interpreter:
from win32com import client
import time
import string
def pathnameToUrl( cPathname):
"""Convert a Windows or Linux pathname into an OOo URL."""
if len( cPathname ) > 1:
if cPathname[1:2] == ":":
cPathname = "/" + cPathname[0] + "|" + cPathname[2:]
cPathname = string.replace( cPathname, "\\", "/" )
cPathname = "file://" + cPathname
return cPathname
def PropertyValueArray(num):
'''Creates an openoffice property value array'''
l = []
for x in range(num):
_p = manager.Bridge_GetStruct("com.sun.star.beans.PropertyValue")
_p.Name = ''
_p.Value = ''
l.append(_p)
return l
wbcpath = r"C:\myexcelfile.xls"
manager = client.DispatchEx("com.sun.star.ServiceManager")
desktop = manager.CreateInstance("com.sun.star.frame.Desktop")
manager._FlagAsMethod("Bridge_GetStruct")
manager._FlagAsMethod("Bridge_GetValueObject")
p = PropertyValueArray(1)
p[0].Name = 'Hidden' # doc should run hidden
p[0].Value = True # doc should run hidden
doc = desktop.loadComponentFromURL(pathnameToUrl(wbcpath), "_blank", 0, p)
doc.store()
time.sleep(5)
doc.dispose()
When I try to schedule this under Windows Task Scheduler on Windows Server Standard 2007 SP2 if get the following error:
Traceback (most recent call last):
File "D:\report_polygon_count.py", line 216, in <module>
manager = client.DispatchEx("com.sun.star.ServiceManager")
File "C:\Python27\ArcGIS10.1\lib\site-packages\win32com\client\__init__.py", line 113, in DispatchEx
dispatch = pythoncom.CoCreateInstanceEx(clsid, None, clsctx, serverInfo, (pythoncom.IID_IDispatch,))[0]
com_error: (-2146959355, 'Server execution failed', None, None)
I am sure the issue is that the application wants to open a window and it is begin rejected because there is no user logged in. I have attempted to run it as hidden to avoid this issue. Is there a way to get round this or is it too ambitious?

Categories

Resources