def write_hms(hms):
try:
with open(FILENAME, "w", newline="") as file:
writer = csv.writer(file,delimiter='|')
writer.writerows(hms)
except OSError as e:
print(type(e), e)
exit_program()
except Exception as e:
print(type(e), e)
exit_program()
Get error:
<class '_csv.Error'> iterable expected, not int
Terminating program.
You have not indented the code correctly but if I copy your code, indent it correctly and specify the variables that you have not defined (like hms and FILENAME) then the code runs without a problem.
import sys
import csv
FILENAME = 'test.csv'
def write_hms(hms):
try:
with open(FILENAME, "w", newline="") as file:
writer = csv.writer(file,delimiter='|')
writer.writerows(hms)
except OSError as e:
print(type(e), e)
sys.exit(1)
except Exception as e:
print(type(e), e)
sys.exit(1)
write_hms(['Spam'] * 5 + ['Baked Beans'])
The error you are getting suggest that you are not passing an 'iterable' like the csv writer is expecting but rather a int. Hence the problem is most likely with the input you are passing in hms and that you are not showing.
If this does not answer your question, please provide a complete, minimal example.
Related
I'm trying to print a text a text file from a webserver in a python program but I am receiving errors. Any help would be greatly appreciated, here is my code:
import RPi.GPIO as GPIO
import urllib2
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(5,GPIO.OUT)
true = 1
while(true):
try:
response = urllib2.urlopen('http://148.251.158.132/k.txt')
status = response.read()
except urllib2.HTTPError, e:
print e.code
except urllib2.URLError, e:
print e.args
print status
if status=='bulbion':
GPIO.output(5,True)
elif status=='bulbioff':
GPIO.output(5,False)
By your comments, it appears your error: "SyntaxError: Missing parentheses in call to print", is caused by excluding parentheses/brackets in your print statements. People usually experience these errors after they update their python version, as the old print statements never required parentheses. The other error: "SyntaxError: unindent does not match any outer indentation level", is because your print statement on line 16 is one space behind all of your other statements on that indentation level, you can fix this problem by moving the print statement one space forward.
Changing your code to this should fix the problems:
import RPi.GPIO as GPIO
import urllib2
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(5,GPIO.OUT)
true = 1
while(true):
try:
response = urllib2.urlopen('http://148.251.158.132/k.txt')
status = response.read()
except urllib2.HTTPError, e:
print (e.code)
except urllib2.URLError, e:
print (e.args)
print (status)
if status=='bulbion':
GPIO.output(5,True)
elif status=='bulbioff':
GPIO.output(5,False)
Hope this helps!
I have written following code I am able to print out the parsed values of Lat and lon but i am unable to write them to a file. I tried flush and also i tried closing the file but of no use. Can somebody point out whats wrong here.
import os
import serial
def get_present_gps():
ser=serial.Serial('/dev/ttyUSB0',4800)
ser.open()
# open a file to write gps data
f = open('/home/iiith/Desktop/gps1.txt', 'w')
data=ser.read(1024) # read 1024 bytes
f.write(data) #write data into file
f = open('/home/iiith/Desktop/gps1.txt', 'r')# fetch the required file
f1 = open('/home/iiith/Desktop/gps2.txt', 'a+')
for line in f.read().split('\n'):
if line.startswith('$GPGGA'):
try:
lat, _, lon= line.split(',')[2:5]
lat=float(lat)
lon=float(lon)
print lat/100
print lon/100
a=[lat,lon]
f1.write(lat+",")
f1.flush()
f1.write(lon+"\n")
f1.flush()
f1.close()
except:
pass
while True:
get_present_gps()
You're covering the error up by using the except: pass. Don't do that... ever. At least log the exception.
One error which it definitely covers is lat+",", which is going to fail because it's float+str and it's not implemented. But there may be more.
So assume I get an error back when using mechanize.Browser.retrieve and I catch it like this:
try:
br.retrieve(url, fname)
except mechanize.HTTPError as e:
if e.code in [403, 404]:
# how can I get to the contents of the server-sent error page?
else:
raise
How can I access the error page which was sent by the server at this point?
I've tried using br.response().get_data(), but that doesn't seem to get populated when using retrieve().
Since HTTP errors are wrapped by mechanize and contain additional info about the response, you can use e.read():
try:
br.retrieve(url, fname)
except mechanize.HTTPError as e:
if e.code in [403, 404]:
print e.read()
else:
raise
I am reading python tutorial here and there is one thing that I can't quite make sense out of. From the docs:
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'has', len(f.readlines()), 'lines'
f.close()
From the explanation in the doc:
The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.
My question is it how does it protect against accidentally catching an exception that wasn't raised in this try block. I don't see what they mean. Can anyone give an example?
One possible alternative approach that you might try is this:
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
print arg, 'has', len(f.readlines()), 'lines'
f.close()
except IOError:
print 'cannot open', arg
Here if there is an exception during f.readlines() or f.close() then it will be caught by the except block and you will get the error message 'cannot open' which is wrong.
I'm trying to make a generic error handler, something like "when others" in Oracle. The examples that I can find all involve catching a specific expected error.
Try:
some_function()
Except: #I don't know what error I'm getting
show_me_error(type_of_error_and_message)
This is very well-documented. But may be you just need Sentry?
try:
1/0
except Exception as e:
print('%s' % type(e))
>>>
integer division or modulo by zero (<type 'exceptions.ZeroDivisionError'>)
import traceback
try:
some_function()
except Exception as e:
message = traceback.format_exc()
print(message)
To print the exception using Python 3, you'll want to use type(e). Example below:
try:
1/0
except Exception as e:
print(type(e))
>>> <class 'ZeroDivisionError'>
And then you can catch the exception with:
try:
1/0
except ZeroDivisionError:
print('Cannot divide by 0')
except Exception as e:
print(type(e))
>>> Cannot divide by 0
To print an exception in Python 3:
try:
# your code
except Exception as e:
print(e)