{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "name": "CPSC217_9System.ipynb", "provenance": [], "collapsed_sections": [ "VJz1Rnz6Ds52", "BdSPoPRUFfSu" ] }, "kernelspec": { "name": "python3", "display_name": "Python 3" } }, "cells": [ { "cell_type": "markdown", "metadata": { "id": "VJz1Rnz6Ds52" }, "source": [ "# Topic 9: System: Command Line Arguments" ] }, { "cell_type": "markdown", "metadata": { "id": "BdSPoPRUFfSu" }, "source": [ "##Arguments" ] }, { "cell_type": "markdown", "metadata": { "id": "PicBZAb5D-v7" }, "source": [ "Code is generally run from command line like\n", "\n", "python program.py\n", "\n", "When you just double click on a file and run it it runs in the same way\n", "\n", "When we do this a special storage area stores the information\n", "\n", "sys.argv = [\"program.py\"]\n", "\n", "However running from command line lets us add arguments\n", "\n", "python program.py filename.txt 3.14 \"Hello, World!\"\n", "\n", "The result of this is \n", "\n", "sys.argv = [\"program.py\",\"filename.txt\",\"3.14\",\"Hello, world!\"]\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "id": "w9ARr8ubElSs" }, "source": [ "One issue we'll have using a notebook here is that we can't actually run a 'program' The whole notebook is a program. For the sake of pretending we have we'll 'hack' the arguments temporarily." ] }, { "cell_type": "code", "metadata": { "id": "26AFQfHPEkv-" }, "source": [ "import sys\n", "\n", "print(sys.argv)\n", "\n", "#Pretend program was run with python myProgram.py 1 string \"string string\"\n", "sys.argv = [\"myProgram.py\", \"1\", \"string\", \"string string\"]\n", "\n", "print(len(sys.argv))\n", "print(sys.argv)\n" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "zcpTkJplFX3c" }, "source": [ "We should always change arguments from string type to the type we expect them to be" ] }, { "cell_type": "code", "metadata": { "id": "VUNwBdXWFWUu" }, "source": [ "import sys\n", "\n", "print(sys.argv)\n", "\n", "#Pretend program was run with python myProgram.py 1 string \"string string\"\n", "sys.argv = [\"myProgram.py\", \"1\", \"string\", \"string string\"]\n", "\n", "print(len(sys.argv))\n", "print(sys.argv)\n", "\n", "print(type(sys.argv[1]))\n", "\n", "arg1 = int(sys.argv[1])\n", "print(type(arg1))" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "whPR8lDOFhgj" }, "source": [ "##Errors" ] }, { "cell_type": "markdown", "metadata": { "id": "eIQbWbdDFp_7" }, "source": [ "The argument list is like any list so we should make sure to loop correctly through it, or access the last spot correctly." ] }, { "cell_type": "code", "metadata": { "id": "SvwyP0Y3FjTD" }, "source": [ "from sys import argv\n", "\n", "#Pretend program was run with python myProgram.py 1 string \"string string\"\n", "argv = [\"myProgram.py\", \"1\", \"string\", \"string string\"]\n", "\n", "i = 0\n", "while i <= len(argv):\n", " print(argv[i])\n", " i+=1" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "Ckhq-4v2FvT7" }, "source": [ "A very common step is to check that the number of arguments is correct" ] }, { "cell_type": "code", "metadata": { "id": "sh-yBi66FzAj" }, "source": [ "import sys\n", "\n", "sys.argv = [\"myProgram.py\", \"1\", \"string\", \"string string\"]\n", "\n", "if len(sys.argv) != 4:\n", " print('Invalid number of arguments')\n", "else:\n", " value1 = sys.argv[1]\n", " print(\"Received\", value1)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "498KgDFcF8Is" }, "source": [ "##Design" ] }, { "cell_type": "code", "metadata": { "id": "1uSSUOSxF7U0" }, "source": [ "import sys\n", "\n", "sys.argv = [\"program.py\",\"filename.txt\",\"3.14\",\"Hello, world!\"]\n", "\n", "EXPECTED_ARG_COUNT = 4\n", "\n", "def main():\n", " if len(sys.argv) != EXPECTED_ARG_COUNT:\n", " print(\"Error: Expect 4 arguments! and got %d\" % len(sys.argv))\n", " return \n", " #Check if data in arguments is right? Exceptions\n", " #Check if files can be accessed\n", " #Then can move on to read files\n", "\n", "main()" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "Mk4W1xfxD0rz" }, "source": [ "# Topic 9: System: Files" ] }, { "cell_type": "markdown", "metadata": { "id": "Ta_FFGL3JP03" }, "source": [ "##Exists\n" ] }, { "cell_type": "code", "metadata": { "id": "G3-A8mYBJRW8" }, "source": [ "import os\n", "import sys\n", "\n", "sys.argv = [\"program.py\",\"filename.txt\",\"3.14\",\"Hello, world!\"]\n", "\n", "print(\"Exists?\", os.path.exists(sys.argv[1]))" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "WTKE_Eg4JekE" }, "source": [ "import os\n", "import sys\n", "\n", "sys.argv = [\"program.py\",\"filename.txt\",\"3.14\",\"Hello, world!\"]\n", "\n", "#Remove file that we don't want to exist because notebook environment will have previous ones around sometimes\n", "if os.path.exists(sys.argv[1]):\n", " os.remove(sys.argv[1])\n", "\n", "print(\"Exists?\", os.path.exists(sys.argv[1]))\n", "\n", "#Make file\n", "file = open(sys.argv[1], \"w\")\n", "file.write(sys.argv[3])\n", "file.close()\n", "\n", "print(\"Exists?\", os.path.exists(sys.argv[1]))" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "UzicHAhYKLhN" }, "source": [ "##Open a file" ] }, { "cell_type": "code", "metadata": { "id": "VyfcGSv1KM8c" }, "source": [ "#For read\n", "file_handle = open(\"filename.txt\")\n", "file_handle.close()\n", "file_handle = open(\"filename.txt\", \"r\")\n", "file_handle.close()" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "3T_U4WR8KRPd" }, "source": [ "#For write\n", "file_handle = open(\"filename.txt\", \"w\")\n", "file_handle.close()" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "2Siq88wLKX0c" }, "source": [ "#For append\n", "file_handle = open(\"filename.txt\", \"a\")\n", "file_handle.close()" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "4totFOubKnOF" }, "source": [ "##Writing" ] }, { "cell_type": "code", "metadata": { "id": "7jzlVZWWKojM" }, "source": [ "filePath = \"inputFile.txt\"\n", "fileHandler = open(filePath, \"w\")\n", "for i in range(5):\n", " fileHandler.write(str(i)+\"\\n\")\n", "fileHandler.close()" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "ZmMv8dvSKbm0" }, "source": [ "##Reading" ] }, { "cell_type": "code", "metadata": { "id": "gYW1rOYeKcvb" }, "source": [ "filePath = \"inputFile.txt\"\n", "fileHandler = open(filePath)\n", "for line in fileHandler:\n", " print(line.rstrip())\n", "fileHandler.close()" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "yMt2O3vgLFAM" }, "source": [ "filePath = \"inputFile.txt\"\n", "fileHandler = open(filePath)\n", "lines = fileHandler.readlines()\n", "fileHandler.close()\n", "\n", "print(lines)\n", "\n", "for line in lines:\n", " print(line.rstrip())\n" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "HgkLCxs5LTSE" }, "source": [ "filePath = \"inputFile.txt\"\n", "fileHandler = open(filePath)\n", "line = fileHandler.readline()\n", "while line != \"\":\n", " print(line.rstrip())\n", " line = fileHandler.readline()\n", "fileHandler.close()" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "gdXuu6mYLhRu" }, "source": [ "filePath = \"inputFile.txt\"\n", "fileHandler = open(filePath)\n", "\n", "print('Current position: %d' % fileHandler.tell())\n", "print('read: <%s>' % fileHandler.read(1)) \n", "print('Current position: %d' % fileHandler.tell())\n", "print('read: <%s>' % fileHandler.read(1)) \n", "\n", "print('Current position: %d' % fileHandler.tell())\n", "print('read: <%s>' % fileHandler.read(1)) \n", "print('Current position: %d' % fileHandler.tell())\n", "print('read: <%s>' % fileHandler.read(1)) \n", "print('Current position: %d' % fileHandler.tell())\n", "\n", "print('read: <%s>' % fileHandler.read(2)) \n", "print('Current position: %d' % fileHandler.tell())\n", "\n", "print('read: <%s>' % fileHandler.read(4)) \n", "print('Current position: %d' % fileHandler.tell())\n", "\n", "fileHandler.seek(0)\n", "print('read: <%s>' % fileHandler.read(4)) \n", "print('Current position: %d' % fileHandler.tell())\n", "\n", "fileHandler.close()" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "ASI4jBk2MFpg" }, "source": [ "filePath = \"inputFile.txt\"\n", "fileHandler = open(filePath, \"w\")\n", "fileHandler.write(\"ID NAME\\n01 Jack\\n02 Mack\\n03 Pham\\n...\")\n", "fileHandler.close()\n", "\n", "fileHandler = open(filePath)\n", "fileHandler.seek(8*3) #skip the first 3 rows (windows stores 1 character end line, use 9 for unix 2 character end lines)\n", "s_id = fileHandler.read(2)\n", "fileHandler.read(1) #skip space\n", "s_name = fileHandler.read(4)\n", "print(\"Student ID: %s, Name: %s.\" % (s_id, s_name))" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "HegmHcPCK4FM" }, "source": [ "##Appending vs Writing" ] }, { "cell_type": "code", "metadata": { "id": "U1rESZJUK3G-" }, "source": [ "filePath = \"inputFile.txt\"\n", "fileHandler = open(filePath, \"w\")\n", "for i in range(5):\n", " fileHandler.write(str(i)+\"\\n\")\n", "fileHandler.close()\n", "\n", "fileHandler = open(filePath)\n", "for line in fileHandler:\n", " print(line.rstrip())\n", "fileHandler.close()\n" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "Lt6usOPWK9Ck" }, "source": [ "filePath = \"inputFile.txt\"\n", "fileHandler = open(filePath, \"w\")\n", "for i in range(5):\n", " fileHandler.write(str(i)+\"\\n\")\n", "fileHandler.close()\n", "\n", "fileHandler = open(filePath, \"w\")\n", "for i in range(5,10):\n", " fileHandler.write(str(i)+\"\\n\")\n", "fileHandler.close()\n", "\n", "fileHandler = open(filePath)\n", "for line in fileHandler:\n", " print(line.rstrip())\n", "fileHandler.close()\n" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "b5DSxaG5LBTM" }, "source": [ "filePath = \"inputFile.txt\"\n", "fileHandler = open(filePath, \"w\")\n", "for i in range(5):\n", " fileHandler.write(str(i)+\"\\n\")\n", "fileHandler.close()\n", "\n", "fileHandler = open(filePath, \"a\")\n", "for i in range(5,10):\n", " fileHandler.write(str(i)+\"\\n\")\n", "fileHandler.close()\n", "\n", "fileHandler = open(filePath)\n", "for line in fileHandler:\n", " print(line.rstrip())\n", "fileHandler.close()\n" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "8YXWmxRaNfgO" }, "source": [ "##Design\n" ] }, { "cell_type": "code", "metadata": { "id": "cYSFOQ5nNgUM" }, "source": [ "import os\n", "import sys\n", "\n", "sys.argv = [\"program.py\",\"filename.txt\",\"3.14\",\"Hello, world!\"]\n", "\n", "EXPECTED_ARG_COUNT = 4\n", "\n", "def main():\n", " if len(sys.argv) != EXPECTED_ARG_COUNT:\n", " sys.stderr.write(\"Error: Expect 4 arguments! and got %d\\n\" % len(sys.argv))\n", " return \n", " #Check if data in arguments is right? Exceptions\n", " #Check if files can be accessed\n", " if not os.path.exists(sys.argv[1]):\n", " sys.stderr.write(\"Error: File does not exist %s\\n\" % sys.argv[1])\n", " return\n", " #Make file\n", " file = open(sys.argv[1], \"w\")\n", " file.write(sys.argv[3])\n", " file.close()\n", " file = open(sys.argv[1], \"r\")\n", " print(file.readlines()[0])\n", " file.close()\n", " \n", "main()\n", "\n" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "hFdFCictD6ob" }, "source": [ "# Topic 9: System: Exceptions" ] }, { "cell_type": "markdown", "metadata": { "id": "OI895To9OFkN" }, "source": [ "Best design is to always use a function to check something instead of letting it 'blow up'" ] }, { "cell_type": "code", "metadata": { "id": "Z-duY_E9OJUO" }, "source": [ "import os\n", "\n", "if not os.path.exists(\"./Folder/There.dat\"):\n", " print(\"File does not exist\")\n", "else:\n", " fileHandler = open(\"./Folder/There.dat\")\n", " print(\"opened There.dat\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "jZ85VEpVGpBU" }, "source": [ "print(\"asdfsd\")\n", "fileHandler = open(\"NotThere.txt\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "oYq4Ta1YOJte" }, "source": [ "\n", "print(\"A\")\n", "\n", "try:\n", " pass\n", "except:\n", " pass\n", "\n", "print(\"D\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "Jl5htioGOtyt" }, "source": [ "However just because we check doesn't mean an exception can't happen" ] }, { "cell_type": "code", "metadata": { "id": "X6QkAcEHOman" }, "source": [ "#CREATING A FILE\n", "file=open(\"inputFile.txt\",\"w\")\n", "file.close()\n", "\n", "from os import path\n", "filePath = \"inputFile.txt\"\n", "if path.exists(filePath): #File exists\n", " print(\"File exists\")\n", " ##File disappears between exist check and opening\n", " os.remove(filePath)\n", " try :\n", " fileHandler = open(filePath) \n", " except:\n", " print(\"File does not exist or can't be accessed!\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "Xr7OH7BoOBAH" }, "source": [ "##Try/Except" ] }, { "cell_type": "code", "metadata": { "id": "-Cg3NsTYPCpk" }, "source": [ "x = [1,2]\n", "try:\n", " int(input(\"asdfds\"))\n", "except:\n", " print(\"Errro\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "x-Y6GUXIPhw9" }, "source": [ "print(\"Always Before\")\n", "\n", "try:\n", " print(\"Always unless this is the line that blows up\")\n", " int(\"sdfgdfgdf\")\n", " print(\"Only if error doesn't occur\")\n", "except:\n", " print(\"Error parsing integer\")\n", "\n", "print(\"Always End\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "nVA48PLVPsZ9" }, "source": [ "print(\"Always\")\n", "try:\n", " print(\"Always unless this is the line that blows up\")\n", " int(\"1\")\n", " print(\"Only if error doesn't occur\")\n", "except:\n", " print(\"Error parsing integer\")\n", "print(\"Always\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "C3ePLQLBPIu-" }, "source": [ "##Naming exceptions" ] }, { "cell_type": "code", "metadata": { "id": "eZabnIv1PLhd" }, "source": [ "try:\n", " int(\"hello\")\n", "except ValueError:\n", " print(\"Error parsing integer\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "OY_6oAQuPN3W" }, "source": [ "try:\n", " int(\"hello\")\n", "except IndexError:\n", " print(\"Error indexing\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "Y5nw585QPSs3" }, "source": [ "try:\n", " x = []\n", " x[10]\n", "except IndexError:\n", " print(\"Error indexing\")\n" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "eH9HacQHPV1w" }, "source": [ "try:\n", " x = 5 / 0\n", "except ZeroDivisionError:\n", " print(\"Error dividing\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "2sbXAimAPzEV" }, "source": [ "##Multiple exceptions through naming" ] }, { "cell_type": "code", "metadata": { "id": "nivMH4BvD4Ir" }, "source": [ "try:\n", " x = input(\"Enter a integer:\")\n", " x = int(x)\n", " print(10/x)\n", "except ZeroDivisionError as error:\n", " print(\"Error dividing\")\n", " print(error)\n", "except ValueError as error:\n", " print(\"Error parsing integer\")\n", " print(error)" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "DHn07nXBQU7n" }, "source": [ "try:\n", " x = input(\"Enter a integer:\")\n", " x = int(x)\n", " print(10/x)\n", "except ValueError:\n", " print(\"Error parsing integer\")\n", "except:\n", " print(\"Any other error\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "KwZoCoPXQZx9" }, "source": [ "try:\n", " x = input(\"Enter a integer:\")\n", " x = int(x)\n", " print(10/x)\n", "except ValueError as e1:\n", " print(\"Error parsing integer: %s\" % e1)\n", "except ZeroDivisionError as e2:\n", " print(\"Error dividing: %s\" % e2)\n", "except:\n", " print(\"Any other error\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "ILey9CM83PM2" }, "source": [ "try:\n", " x = input(\"Enter a integer:\")\n", " x = int(x)\n", " print(10/x)\n", "except (ValueError, ZeroDivisionError) as error:\n", " print(\"Either value or zero division occurred: %s\" % error)\n", "except:\n", " print(\"Any other error\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "VEj1vwihQqXb" }, "source": [ "try:\n", " userInput = input(\">Enter an int != 0: \")\n", " value = int(userInput) \n", " print(1/value)\n", "except ValueError as value_error:\n", " print(\"ValueError: User input %s is not an int.\" % userInput)\n", "except ZeroDivisionError as div_by_zero_except:\n", " print(\"ZeroDivisionError - Cannot divide by Zero\")\n", "except:\n", " print(\"Something else went wrong!\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "2DJopuT2QzH2" }, "source": [ "##Try/Except/If" ] }, { "cell_type": "code", "metadata": { "id": "zoWRW-2-Q0w-" }, "source": [ "x = 1\n", "del x\n", "\n", "try:\n", " userInput = input(\">Enter an int >0: \")\n", " value = int(userInput)\n", " print(\"End of Try clause.\")\n", " x = value * 2\n", "except:\n", " print(\"Error\")\n", " sys.exit(1)\n", "else:\n", " print(\"In else clause: No exception occurred\")\n", " print(\"value: %d\" % (value / 10))\n", " print(x)\n", "\n", "print(\"END\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "seHIhZ4WRJOo" }, "source": [ "try:\n", " userInput = input(\">Enter an int >0: \")\n", " value = int(userInput)#<- potential ValueError\n", " print(\"End of Try clause.\")\n", "except Exception as e:\n", " print(e)\n", "else:\n", " print(\"In else clause: No exception occurred and following statement is unprotected\")\n", " x = value/0" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "qVLeyCUxRXg1" }, "source": [ "##Try/Exception/Finally" ] }, { "cell_type": "code", "metadata": { "id": "M15v5OMpPOz9" }, "source": [ "try:\n", " userInput = input(\">Enter an int >0: \")\n", " value = int(userInput)\n", "except ValueError as value_error:\n", " print(value_error)\n", "finally:\n", " print(\"In finally clause.\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "TJrCS1GvTqXt" }, "source": [ "try:\n", " userInput = input(\">Enter an int >0: \")\n", " inf = open(userInput)\n", " for line in inf:\n", " print(line)\n", " inf.close()\n", "except :\n", " print(\"error\")\n", "\n" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "gRs_0UVnRYzT" }, "source": [ "def foo():\n", " try:\n", " userInput = input(\"Enter an int: \")\n", " value = int(userInput)\n", " return value\n", " except ValueError as value_error:\n", " print(value_error)\n", " return None\n", " finally:\n", " print(\"In finally clause.\")\n", " \n", "print(\"foo() returned: %s\" % foo())" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "ruBDjJdURefo" }, "source": [ "def foo():\n", " try:\n", " userInput = input(\"Enter an int: \")\n", " value = int(userInput)\n", " return value\n", " except ValueError as value_error:\n", " print(value_error)\n", " return None\n", " finally:\n", " print(\"In finally clause.\")\n", " return -1\n", " \n", "print(\"foo() returned: %s \" % foo())" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "qNMiwTIFRM3S" }, "source": [ "try:\n", " file_handler = open(\"input.txt\")\n", " for line in file_handle:\n", " line = line.strip()\n", " int(line)\n", "except:\n", " print(\"Error parsing file\")\n", "finally:\n", " #cleanup\n", " file_handler.close()\n" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "RQbReh157j0A" }, "source": [ "def main():\n", " try: \n", " open(\"NotThere.txt\")\n", " except Exception:\n", " print(\"Error\")\n", " sys.exit(1)\n", "\n", "main()\n" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "QUn-UWoxRpbn" }, "source": [ "##Exit" ] }, { "cell_type": "markdown", "metadata": { "id": "eDp6W_sTRtfu" }, "source": [ "Lets you end a program immediately (The program quitting has a value attached (0) is considered exitting ok, any other value is considered error code." ] }, { "cell_type": "code", "metadata": { "id": "O9X3UgY9RuFY" }, "source": [ "import sys\n", "def div(a, b):\n", " if not isinstance(a, int) or not isinstance(b, int):\n", " sys.exit(-123)\n", " if b == 0:\n", " sys.exit(123)\n", " return a/b\n", "\n", "div(1, 2)" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "mTFJZYfhR5nv" }, "source": [ "import sys\n", "def div(a, b):\n", " if not isinstance(a, int) or not isinstance(b, int):\n", " sys.exit(-123)\n", " if b == 0:\n", " sys.exit(123)\n", " return a/b\n", "div(1, 0)" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "DZikDKTIR8wH" }, "source": [ "import sys\n", "def div(a, b):\n", " if not isinstance(a, int) or not isinstance(b, int):\n", " sys.exit(-123)\n", " if b == 0:\n", " sys.exit(123)\n", " return a/b\n", "div(1, 1)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "18_0J_AeSDUH" }, "source": [ "##Raise an exception (function design)" ] }, { "cell_type": "code", "metadata": { "id": "Iho4u7GiSFme" }, "source": [ "import sys\n", "\n", "def repeatStar(number):\n", " if not isinstance(number, int):\n", " raise Exception('%s not an int' % number)\n", " if number == 0:\n", " raise ValueError('parameter number is zero')\n", " return number*\"*\"\n", "\n", "try:\n", " repeatStar(1.5)\n", "except (ValueError, Exception) as detail:\n", " print(detail) " ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "HRzW_8lZSNdB" }, "source": [ "import sys\n", "\n", "def repeatStar(number):\n", " if not isinstance(number, int):\n", " raise Exception('%s not an int' % number)\n", " if number == 0:\n", " raise ValueError('parameter number is zero')\n", " return number*\"*\"\n", "\n", "try:\n", " repeatStar(0)\n", "except (ValueError, Exception) as detail:\n", " print(detail) " ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "asCipHERSQOI" }, "source": [ "import sys\n", "\n", "def repeatStar(number):\n", " if not isinstance(number, int):\n", " raise Exception('%s not an int' % number)\n", " if number == 0:\n", " raise ValueError('parameter number is zero')\n", " return number*\"*\"\n", "\n", "try:\n", " repeatStar(1)\n", "except (ValueError, Exception) as detail:\n", " print(detail) " ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "KmxSYLogSWNX" }, "source": [ "##Design" ] }, { "cell_type": "code", "metadata": { "id": "f3qNBY0RSXDg" }, "source": [ "import os\n", "import sys\n", "\n", "sys.argv = [\"program.py\",\"filename.txt\",\"3.14\",\"Hello, world!\"]\n", "\n", "EXPECTED_ARG_COUNT = 4\n", "\n", "def main():\n", " if len(sys.argv) != EXPECTED_ARG_COUNT:\n", " print(\"Error: Expect 4 arguments! and got %d\" % len(sys.argv))\n", " sys.exit(1)\n", " try:\n", " x = float(sys.argv[2])\n", " print(\"Float argument was: %.2f\" % x)\n", " except ValueError:\n", " print(\"Error second argument %s is not a float.\" % sys.argv[2])\n", " sys.exit(1)\n", " if not os.path.exists(sys.argv[1]):\n", " print(\"Error: File does not exist %s\" % sys.argv[1])\n", " sys.exit(1)\n", "\n", " #Make file\n", " try:\n", " file = open(sys.argv[1], \"w\")\n", " file.write(sys.argv[3])\n", " except:\n", " print(\"Error: Error writing to file!\")\n", " sys.exit(1)\n", " finally:\n", " file.close()\n", " try:\n", " file = open(sys.argv[1], \"r\")\n", " print(file.readlines()[0])\n", " except:\n", " print(\"Error: Error reading from file!\")\n", " sys.exit(1)\n", " finally:\n", " file.close()\n", " \n", "main()\n", "\n" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "3a5YjfPXhZtJ" }, "source": [ "def reverseLines(inFilename, outFilename):\n", "\n", " try:\n", " inFile = open(inFilename,'r')\n", " except IOError:\n", " sys.exit(\"Encountered problem\")\n", "\n", " try:\n", " outFile = open(outFilename,'w')\n", " except IOError:\n", " sys.exit(\"Encountered problem\")\n", " finally:\n", " inFile.close()\n", " \n", " try:\n", " for line in inFile:\n", " line = line.rstrip()\n", " outFile.write(line[::-1] + \"\\n\")\n", " except IOError:\n", " print(\"Encountered problem\")\n", " finally:\n", " inFile.close()\n", " outFile.close()\n", "\n", "reverseLines(\"asdfsd.txt\",\"ReverseNames.txt\")" ], "execution_count": null, "outputs": [] } ] }