Skip to content

Commit 031aaac

Browse files
thezoggyPatrick Vos
authored andcommitted
Change open to 'with open' and exception IOError to 'EnvironmentError'
Use 'with open' when opening/writing files http://sdqali.in/blog/2012/07/09/understanding-pythons-with/ The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too. Switch exception to `EnvironmentError` http://docs.python.org/2/library/exceptions.html#exceptions.EnvironmentError Since it is the parent of IOError, OSError *and* WindowsError where available. + Cleanup test_lib a bit, still needs work. + Applied whitespace PEP8 fixes to the files touched. closes midgetspygh-797
1 parent e3bdb14 commit 031aaac

File tree

11 files changed

+154
-121
lines changed

11 files changed

+154
-121
lines changed

sickbeard/helpers.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,15 @@
1616
# You should have received a copy of the GNU General Public License
1717
# along with Sick Beard. If not, see <http://www.gnu.org/licenses/>.
1818

19+
from __future__ import with_statement
20+
1921
import gzip
2022
import os
2123
import re
2224
import shutil
2325
import socket
2426
import stat
2527
import StringIO
26-
import sys
2728
import time
2829
import traceback
2930
import urllib
@@ -460,7 +461,7 @@ def chmodAsParent(childPath):
460461
return
461462

462463
childPath_owner = childPathStat.st_uid
463-
user_id = os.geteuid() #only available on UNIX
464+
user_id = os.geteuid() # @UndefinedVariable - only available on UNIX
464465

465466
if user_id != 0 and user_id != childPath_owner:
466467
logger.log(u"Not running as root or owner of " + childPath + ", not trying to set permissions", logger.DEBUG)
@@ -498,14 +499,14 @@ def fixSetGroupID(childPath):
498499
return
499500

500501
childPath_owner = childStat.st_uid
501-
user_id = os.geteuid() #only available on UNIX
502+
user_id = os.geteuid() # @UndefinedVariable - only available on UNIX
502503

503504
if user_id != 0 and user_id != childPath_owner:
504505
logger.log(u"Not running as root or owner of " + childPath + ", not trying to set the set-group-ID", logger.DEBUG)
505506
return
506507

507508
try:
508-
ek.ek(os.chown, childPath, -1, parentGID) #@UndefinedVariable - only available on UNIX
509+
ek.ek(os.chown, childPath, -1, parentGID) # @UndefinedVariable - only available on UNIX
509510
logger.log(u"Respecting the set-group-ID bit on the parent directory for %s" % (childPath), logger.DEBUG)
510511
except OSError:
511512
logger.log(u"Failed to respect the set-group-ID bit on the parent directory for %s (setting group ID %i)" % (childPath, parentGID), logger.ERROR)
@@ -545,8 +546,8 @@ def create_https_certificates(ssl_cert, ssl_key):
545546
Create self-signed HTTPS certificares and store in paths 'ssl_cert' and 'ssl_key'
546547
"""
547548
try:
548-
from OpenSSL import crypto #@UnresolvedImport
549-
from lib.certgen import createKeyPair, createCertRequest, createCertificate, TYPE_RSA, serial #@UnresolvedImport
549+
from OpenSSL import crypto # @UnresolvedImport
550+
from lib.certgen import createKeyPair, createCertRequest, createCertificate, TYPE_RSA, serial # @UnresolvedImport
550551
except:
551552
logger.log(u"pyopenssl module missing, please install for https access", logger.WARNING)
552553
return False

sickbeard/metadata/generic.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
# You should have received a copy of the GNU General Public License
1717
# along with Sick Beard. If not, see <http://www.gnu.org/licenses/>.
1818

19+
from __future__ import with_statement
20+
1921
import os.path
2022

2123
import xml.etree.cElementTree as etree
@@ -842,8 +844,8 @@ def retrieveShowMetadata(self, folder):
842844
logger.log(u"Loading show info from metadata file in " + folder, logger.DEBUG)
843845

844846
try:
845-
xmlFileObj = ek.ek(open, metadata_path, 'r')
846-
showXML = etree.ElementTree(file=xmlFileObj)
847+
with ek.ek(open, metadata_path, 'r') as xmlFileObj:
848+
showXML = etree.ElementTree(file=xmlFileObj)
847849

848850
if showXML.findtext('title') == None or (showXML.findtext('tvdbid') == None and showXML.findtext('id') == None):
849851
logger.log(u"Invalid info in tvshow.nfo (missing name or id):" \
@@ -866,7 +868,7 @@ def retrieveShowMetadata(self, folder):
866868
return empty_return
867869

868870
except Exception, e:
869-
logger.log(u"There was an error parsing your existing metadata file: " + ex(e), logger.WARNING)
871+
logger.log(u"There was an error parsing your existing metadata file: '" + metadata_path + "' error: " + ex(e), logger.WARNING)
870872
return empty_return
871873

872874
return (tvdb_id, name)

sickbeard/metadata/tivo.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
# You should have received a copy of the GNU General Public License
1818
# along with Sick Beard. If not, see <http://www.gnu.org/licenses/>.
1919

20+
from __future__ import with_statement
21+
2022
import datetime
2123
import os
2224

@@ -25,6 +27,7 @@
2527
from sickbeard import logger, exceptions, helpers
2628
from sickbeard.metadata import generic
2729
from sickbeard import encodingKludge as ek
30+
from sickbeard.exceptions import ex
2831

2932
from lib.tvdb_api import tvdb_api, tvdb_exceptions
3033

@@ -309,14 +312,15 @@ def write_ep_file(self, ep_obj):
309312
helpers.chmodAsParent(nfo_file_dir)
310313

311314
logger.log(u"Writing episode nfo file to " + nfo_file_path, logger.DEBUG)
312-
nfo_file = ek.ek(open, nfo_file_path, 'w')
313315

314-
# Calling encode directly, b/c often descriptions have wonky characters.
315-
nfo_file.write(data.encode("utf-8"))
316-
nfo_file.close()
316+
with ek.ek(open, nfo_file_path, 'w') as nfo_file:
317+
# Calling encode directly, b/c often descriptions have wonky characters.
318+
nfo_file.write(data.encode("utf-8"))
319+
317320
helpers.chmodAsParent(nfo_file_path)
318-
except IOError, e:
319-
logger.log(u"Unable to write file to " + nfo_file_path + " - are you sure the folder is writable? " + str(e).decode('utf-8'), logger.ERROR)
321+
322+
except EnvironmentError, e:
323+
logger.log(u"Unable to write file to " + nfo_file_path + " - are you sure the folder is writable? " + ex(e), logger.ERROR)
320324
return False
321325

322326
return True

sickbeard/nzbSplitter.py

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,9 @@
1616
# You should have received a copy of the GNU General Public License
1717
# along with Sick Beard. If not, see <http://www.gnu.org/licenses/>.
1818

19-
import urllib2
19+
from __future__ import with_statement
2020

21+
import urllib2
2122
import xml.etree.cElementTree as etree
2223
import xml.etree
2324
import re
@@ -26,14 +27,17 @@
2627

2728
from sickbeard import logger, classes, helpers
2829
from sickbeard.common import Quality
30+
from sickbeard import encodingKludge as ek
31+
from sickbeard.exceptions import ex
32+
2933

3034
def getSeasonNZBs(name, urlData, season):
3135

3236
try:
3337
showXML = etree.ElementTree(etree.XML(urlData))
3438
except SyntaxError:
35-
logger.log(u"Unable to parse the XML of "+name+", not splitting it", logger.ERROR)
36-
return ({},'')
39+
logger.log(u"Unable to parse the XML of " + name + ", not splitting it", logger.ERROR)
40+
return ({}, '')
3741

3842
filename = name.replace(".nzb", "")
3943

@@ -43,10 +47,10 @@ def getSeasonNZBs(name, urlData, season):
4347

4448
sceneNameMatch = re.search(regex, filename, re.I)
4549
if sceneNameMatch:
46-
showName, qualitySection, groupName = sceneNameMatch.groups() #@UnusedVariable
50+
showName, qualitySection, groupName = sceneNameMatch.groups() # @UnusedVariable
4751
else:
48-
logger.log(u"Unable to parse "+name+" into a scene name. If it's a valid one log a bug.", logger.ERROR)
49-
return ({},'')
52+
logger.log(u"Unable to parse " + name + " into a scene name. If it's a valid one log a bug.", logger.ERROR)
53+
return ({}, '')
5054

5155
regex = '(' + re.escape(showName) + '\.S%02d(?:[E0-9]+)\.[\w\._]+\-\w+' % season + ')'
5256
regex = regex.replace(' ', '.')
@@ -72,6 +76,7 @@ def getSeasonNZBs(name, urlData, season):
7276

7377
return (epFiles, xmlns)
7478

79+
7580
def createNZBString(fileElements, xmlns):
7681

7782
rootElement = etree.Element("nzb")
@@ -86,12 +91,16 @@ def createNZBString(fileElements, xmlns):
8691

8792
def saveNZB(nzbName, nzbString):
8893

89-
nzb_fh = open(nzbName+".nzb", 'w')
90-
nzb_fh.write(nzbString)
91-
nzb_fh.close()
94+
try:
95+
with ek.ek(open, nzbName + ".nzb", 'w') as nzb_fh:
96+
nzb_fh.write(nzbString)
97+
98+
except EnvironmentError, e:
99+
logger.log(u"Unable to save NZB: " + ex(e), logger.ERROR)
100+
92101

93102
def stripNS(element, ns):
94-
element.tag = element.tag.replace("{"+ns+"}", "")
103+
element.tag = element.tag.replace("{" + ns + "}", "")
95104
for curChild in element.getchildren():
96105
stripNS(curChild, ns)
97106

@@ -103,15 +112,15 @@ def splitResult(result):
103112
urlData = helpers.getURL(result.url)
104113

105114
if urlData is None:
106-
logger.log(u"Unable to load url "+result.url+", can't download season NZB", logger.ERROR)
115+
logger.log(u"Unable to load url " + result.url + ", can't download season NZB", logger.ERROR)
107116
return False
108117

109118
# parse the season ep name
110119
try:
111120
np = NameParser(False)
112121
parse_result = np.parse(result.name)
113122
except InvalidNameException:
114-
logger.log(u"Unable to parse the filename "+result.name+" into a valid episode", logger.WARNING)
123+
logger.log(u"Unable to parse the filename " + result.name + " into a valid episode", logger.WARNING)
115124
return False
116125

117126
# bust it up
@@ -123,28 +132,28 @@ def splitResult(result):
123132

124133
for newNZB in separateNZBs:
125134

126-
logger.log(u"Split out "+newNZB+" from "+result.name, logger.DEBUG)
135+
logger.log(u"Split out " + newNZB + " from " + result.name, logger.DEBUG)
127136

128137
# parse the name
129138
try:
130139
np = NameParser(False)
131140
parse_result = np.parse(newNZB)
132141
except InvalidNameException:
133-
logger.log(u"Unable to parse the filename "+newNZB+" into a valid episode", logger.WARNING)
142+
logger.log(u"Unable to parse the filename " + newNZB + " into a valid episode", logger.WARNING)
134143
return False
135144

136145
# make sure the result is sane
137146
if (parse_result.season_number != None and parse_result.season_number != season) or (parse_result.season_number == None and season != 1):
138-
logger.log(u"Found "+newNZB+" inside "+result.name+" but it doesn't seem to belong to the same season, ignoring it", logger.WARNING)
147+
logger.log(u"Found " + newNZB + " inside " + result.name + " but it doesn't seem to belong to the same season, ignoring it", logger.WARNING)
139148
continue
140149
elif len(parse_result.episode_numbers) == 0:
141-
logger.log(u"Found "+newNZB+" inside "+result.name+" but it doesn't seem to be a valid episode NZB, ignoring it", logger.WARNING)
150+
logger.log(u"Found " + newNZB + " inside " + result.name + " but it doesn't seem to be a valid episode NZB, ignoring it", logger.WARNING)
142151
continue
143152

144153
wantEp = True
145154
for epNo in parse_result.episode_numbers:
146155
if not result.extraInfo[0].wantEpisode(season, epNo, result.quality):
147-
logger.log(u"Ignoring result "+newNZB+" because we don't want an episode that is "+Quality.qualityStrings[result.quality], logger.DEBUG)
156+
logger.log(u"Ignoring result " + newNZB + " because we don't want an episode that is " + Quality.qualityStrings[result.quality], logger.DEBUG)
148157
wantEp = False
149158
break
150159
if not wantEp:
@@ -164,4 +173,4 @@ def splitResult(result):
164173

165174
resultList.append(curResult)
166175

167-
return resultList
176+
return resultList

sickbeard/providers/generic.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
# You should have received a copy of the GNU General Public License
1717
# along with Sick Beard. If not, see <http://www.gnu.org/licenses/>.
1818

19+
from __future__ import with_statement
1920

2021
import datetime
2122
import os
@@ -139,11 +140,10 @@ def downloadResult(self, result):
139140
logger.log(u"Saving to " + file_name, logger.DEBUG)
140141

141142
try:
142-
fileOut = open(file_name, writeMode)
143-
fileOut.write(data)
144-
fileOut.close()
143+
with open(file_name, writeMode) as fileOut:
144+
fileOut.write(data)
145145
helpers.chmodAsParent(file_name)
146-
except IOError, e:
146+
except EnvironmentError, e:
147147
logger.log(u"Unable to save the file: " + ex(e), logger.ERROR)
148148
return False
149149

0 commit comments

Comments
 (0)