Skip to content
Snippets Groups Projects
03_file_management.ipynb 44.2 KiB
Newer Older
    "\n",
    "<a class=\"anchor\" id=\"solutions\"></a>\n",
    "### Solutions\n",
    "\n",
    "\n",
    "Use the `print_solution` function, defined below, to print the solution for a\n",
    "specific exercise."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pygments import highlight\n",
    "from pygments.lexers import PythonLexer\n",
    "from pygments.formatters import HtmlFormatter\n",
    "import IPython\n",
    "\n",
    "# Pass the title of the exercise you\n",
    "# are interested to this function\n",
    "def print_solution(extitle):\n",
    "    solfile = ''.join([c.lower() if c.isalnum() else '_' for c in extitle])\n",
    "    solfile = op.join('.solutions', '{}.py'.format(solfile))\n",
    "\n",
    "    if not op.exists(solfile):\n",
    "        print('Can\\'t find solution to exercise \"{}\"'.format(extitle))\n",
    "        return\n",
    "\n",
    "    with open(solfile, 'rt') as f:\n",
    "        code = f.read()\n",
    "\n",
    "    formatter = HtmlFormatter()\n",
    "    return IPython.display.HTML('<style type=\"text/css\">{}</style>{}'.format(\n",
    "        formatter.get_style_defs('.highlight'),\n",
    "        highlight(code, PythonLexer(), formatter)))"
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a class=\"anchor\" id=\"appendix-exceptions\"></a>\n",
    "## Appendix: Exceptions\n",
    "\n",
    "\n",
    "At some point in your life, a piece of code that you write is inevitably going\n",
    "to fail, and you are going to have to deal with it. This is particularly\n",
    "relevant to file management tasks - many of the functions that have been\n",
    "introduced in this practical can fail for all kinds of reasons, such as\n",
    "incorrect permissions or ownership, lack of disk space, or a network file\n",
    "system going down.\n",
    "\n",
    "\n",
    "Any statement in Python can potentially result in an error. When a line of\n",
    "code triggers an error, we say that it _raises_ the error (a.k.a. _throws_ in\n",
    "other languages). When an error occurs, an `Exception` object is raised,\n",
    "causing execution to stop at the line that caused the error:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = [1, 2, 3]\n",
    "a.remove(4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The word `Exception` is used instead of `Error` because not all exceptions are\n",
    "errors. For example, when you type CTRL+C into a running Python program, a\n",
    "`KeyboardInterrupt` exception will be raised.\n",
    "\n",
    "\n",
    "> There are many different types of exceptions in Python - a list of all the\n",
    "> built-in ones can be found\n",
    "> [here](https://docs.python.org/3.5/library/exceptions.html). It is also easy\n",
    "> to define your own exceptions by creating a sub-class of `Exception` (beyond\n",
    "> the scope of this practical).\n",
    "\n",
    "\n",
    "Fortunately Python gives us the capability to _catch_ exceptions when they are\n",
    "raised, using the `try` and `except` keywords. As an example, let's say that\n",
    "the user asked our program to create a directory somewhere on the file system.\n",
    "A real program would need to handle situations in which that directory cannot\n",
    "be created - we might do it like this in Python:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "dirpath = '/sbin/foo'\n",
    "\n",
    "try:\n",
    "    os.mkdir(dirpath)\n",
    "\n",
    "except OSError as e:\n",
    "    print('Could not create {}! Reason: {}'.format(dirpath, e))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this example, we have put the `os.mkdir` call inside a `try:` block. Now,\n",
    "if it raises an `Exception` of type `OSError`, that `OSError` will be _caught_\n",
    "and passed to the `except:` block. A `try` block must always followed by an\n",
    "`except` block (and/or a `finally` block - keep reading).\n",
    "\n",
    "\n",
    "The `except OSError as e:` line means: _if any code in the `try` block raises\n",
    "an `Exception` of type `OSError`, then catch it, assign it to a variable\n",
    "called `e`, and pass it to the code inside the `except` block._\n",
    "\n",
    "\n",
    "### Catching different types of exceptions\n",
    "\n",
    "\n",
    "It is common for a piece of code to have the potential to raise different\n",
    "types of exceptions. Python allows you to have multiple `except` blocks\n",
    "associated with a single `try` block, so you can handle different types of\n",
    "exceptions in different ways. For example, you might want to print a useful\n",
    "error message so the user knows what has gone wrong:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numerator   = '123'\n",
    "denominator = 0\n",
    "\n",
    "try:\n",
    "    numerator = float(numerator)\n",
    "    print(numerator / denominator)\n",
    "\n",
    "except TypeError as e:\n",
    "    print('Numerator and/or denominator are of the wrong type!')\n",
    "    print('  ', e)\n",
    "\n",
    "except ValueError as e:\n",
    "    print('Numerator is not a float!')\n",
    "    print('  ', e)\n",
    "\n",
    "# Note that specifying a variable to refer\n",
    "# to the Exception object is optional.\n",
    "except ZeroDivisionError:\n",
    "    print('Denominator is zero!')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Experiment with the above code block - try out different values for the\n",
    "`numerator` and `denominator`, and see what happens.\n",
    "\n",
    "\n",
    "You can also specify different types of exceptions in a single `except`\n",
    "statement:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numerator   = '123'\n",
    "denominator = 0\n",
    "try:\n",
    "    numerator = float(numerator)\n",
    "    print(numerator / denominator)\n",
    "\n",
    "except (TypeError, ZeroDivisionError) as e:\n",
    "    print('Numerator and/or denominator are of the '\n",
    "          'wrong type, or the denominator is zero!')\n",
    "    print('  ', e)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The catch-all approach\n",
    "\n",
    "\n",
    "Instead of specifying all of the different types of exceptions that could\n",
    "occur, it is possible to simply use a single `except` block to catch all\n",
    "exceptions of type `Exception`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numerator   = 'abc'\n",
    "denominator = 1\n",
    "\n",
    "try:\n",
    "    numerator = float(numerator)\n",
    "    print(numerator / denominator)\n",
    "\n",
    "except Exception as e:\n",
    "    print('Something is wrong with numerator or denominator!')\n",
    "    print('  ', e)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It is generally better practice to be as specific as possible when you are\n",
    "catching exceptions, but sometimes all you care about is whether your code\n",
    "worked or didn't, and in this case the you can simply use this catch-all\n",
    "approach.\n",
    "\n",
    "\n",
    "__Warning:__ Even though it is possible to, you should __never__ write a\n",
    "`try`-`except` block like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    # do stuff\n",
    "    pass\n",
    "\n",
    "except:\n",
    "    # handle exceptions\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You don't actually have to specify any exception type in an `except`\n",
    "statement.  But you should never do this!  As we have already mentioned, not\n",
    "all exceptions are errors. The above code will catch _all_ exceptions, even\n",
    "those which do not inherit from the standard `Exception` class. This includes\n",
    "important exceptions such as `KeyboardInterrupt` and `SystemExit`, which\n",
    "control important aspects of your program's behaviour.\n",
    "\n",
    "\n",
    "So you should always, at the very least, specify the `Exception` type:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    # do stuff\n",
    "    pass\n",
    "\n",
    "except Exception:\n",
    "    # handle exceptions\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The `finally` keyword\n",
    "\n",
    "\n",
    "Sometimes, when you are performing a task, you might have some clean-up logic\n",
    "that must be executed regardless of whether the task succeeded or failed. The\n",
    "canonical example here is that if you open a file, you must make sure that to\n",
    "close it when you are finished, otherwise its contents may be corrupted."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = open('raw_mri_data/subj_1/t1.nii', 'rb')\n",
    "try:\n",
    "    f.write('ho hum')\n",
    "\n",
    "except IOError as e:\n",
    "    print('Error occurred!: ', e)\n",
    "finally:\n",
    "    print('Closing file')\n",
    "    f.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It is possible to use `try` and `finally` without an `except` block. This is\n",
    "useful if you have some code that needs some clean-up logic, but you don't\n",
    "actually want to catch the exception - sometimes it is better for a program\n",
    "to crash, rather than for errors to be silently suppressed, because it can\n",
    "be easier to figure out what went wrong:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = open('raw_mri_data/subj_1/t1.nii', 'rb')\n",
    "\n",
    "try:\n",
    "    f.write('ho hum')\n",
    "\n",
    "finally:\n",
    "    print('Closing file')\n",
    "    f.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> The above was just an example - it is generally better practice to use the\n",
    "> `with` statement when opening files.\n",
    "\n",
    "\n",
    "You can read more about handling exceptions in Python\n",
    "[here](https://docs.python.org/3.5/tutorial/errors.html).\n",
    "\n",
    "\n",
    "### Raising exceptions\n",
    "\n",
    "\n",
    "It is possible to generate your own exception at any point by using the\n",
    "`raise` keyword, and passing it an `Exception` object:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "raise Exception('Kaboom!')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This can be useful if your code detects that something has gone wrong, and\n",
    "needs to abort.\n",
    "\n",
    "\n",
    "You can also raise an existing `Exception` from within an `except` block:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    print(1 / 0)\n",
    "\n",
    "except Exception:\n",
    "    print('Some error occurred!')\n",
    "    raise"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This can be useful if you want to print a message when an exception occurs,\n",
    "but also allow the execption to be propagated upwards."
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}