{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Introduction to Terminal apps as well as **pickle()**\n", "A terminal app is an application which runs on simple terminal.
\n", "We have see how it works via *print()* and *input()*.
\n", "Terminal apps are quite useful in the world of **Linux & Mac**.
\n", "Some examples of apps in **Linux & Mac** are:\n", "- *top*: which shows the running processes\n", "- *vi* or *pico* or *nano* or *emacs*: which are some popular text editors\n", "\n", "Let's examine how we can create some *simple* terminal apps.\n", "\n", "**Created and edited** by John C.S. Lui, August 9th, 2020\n", "\n", "**Important note**: If you want to use and modify this notebook file, please acknowledge the author." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Import the sleep function.\n", "from time import sleep\n", "\n", "# Display a title bar.\n", "print(\"\\t**********************************************\")\n", "print(\"\\t*** Hello to my students in CSCI2040! ***\")\n", "print(\"\\t**********************************************\\n\\n\")\n", "\n", "# Generate a series of output\n", "for x in range(0,11): #generate 11 numbers from 0 to 10\n", " print(\"See, I know how to count: %d\" %x)\n", " \n", "# Let's invoke the sleep function to \"pause\" for secs seconds\n", "secs = int(input(\"Please enter the # of seconds you want me to sleep:\")) # request input\n", "print(\"Going to sleep now .....\")\n", "sleep(secs)\n", "print (\"Great, I had a %d secs of nap during the lecture of CSCI2040, it feels great!\" %secs)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Creating a simple greater terminal program\n", "\n", " **REMEMBER TO SHOW THIS ON A TERMINAL !!!!!!**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# import some functions and libaries for our use\n", "from time import sleep \n", "import os\n", "\n", "# Greeter is a terminal application that greets students,\n", "# and remembers new students, if any.\n", "\n", "# Display a title bar.\n", "print(\"\\t**********************************************************\")\n", "print(\"\\t*** Greeter - Hello old and new students of CSCI2040 ***\")\n", "print(\"\\t**********************************************************\")\n", "\n", "sleep(3) # Let's sleep for 3 seconds first\n", "\n", "# Print a bunch of information, in short intervals\n", "students = ['mary', 'nancy', 'elaine', 'susan', 'joey']\n", "\n", "# Print each name 3 times.\n", "for name in students:\n", " # Clear the screen before listing names.\n", " os.system('clear')\n", " \n", " # Display the title bar.\n", " print(\"\\t**********************************************\")\n", " print(\"\\t*** Greeter - Hello old and new friends! ***\")\n", " print(\"\\t**********************************************\")\n", "\n", " print(\"\\n\\n\")\n", " for x in range(0,3):\n", " print(\"Hello \" + name.title(), \"how are you doing?\")\n", " \n", " # Pause for 1 second between batches.\n", " sleep(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Another example" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# ************ TRY THIS ON A COMPUTER **************\n", "\n", "from time import sleep \n", "import os\n", "\n", "# define a display function\n", "def display_title_bar():\n", " # Clears the terminal screen, and displays a title bar.\n", " os.system('clear')\n", " \n", " print(\"\\t**********************************************\")\n", " print(\"\\t*** TITLE BAR ***\")\n", " print(\"\\t**********************************************\")\n", " \n", "\n", "\n", "# Let us create a loop such that users can choose various options.\n", "\n", "selection = '' # initialize the selection\n", "while selection != 'q': \n", " display_title_bar()\n", " \n", " # Display options for users\n", " print(\"\\n[1] Meet a new friend.\")\n", " print(\"[2] Talk to an existing friend.\")\n", " print(\"[q] Quit.\")\n", " \n", " selection = input(\"\\nPlease selection the above options: \")\n", " \n", " # Based on the user's selection, provide proper response\n", " if selection == '1':\n", " print(\"\\nHere is Lulu, your new friend.\\n\")\n", " sleep(3) # Let's sleep for 3 seconds first\n", " elif selection == '2':\n", " print(\"\\nHere is Mary, you have met her last week!\\n\")\n", " sleep(3) # Let's sleep for 3 seconds first\n", " elif selection == 'q':\n", " print(\"\\nThanks for playing. Bye.\")\n", " else:\n", " print(\"\\nIllegal option !!\\n\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Let's extend the above program" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# ************ TRY THIS ON A COMPUTER **************\n", "\n", "from time import sleep \n", "import os\n", "\n", "# define a display function\n", "def display_title_bar():\n", " # Clears the terminal screen, and displays a title bar.\n", " os.system('clear')\n", " \n", " print(\"\\t**********************************************\")\n", " print(\"\\t*** TITLE BAR ***\")\n", " print(\"\\t**********************************************\")\n", " \n", "\n", "def get_user_selection():\n", "# Let users know what they can do.\n", " print(\"\\n[1] Meet a new friend.\")\n", " print(\"[2] Talk to an existing friend.\")\n", " print(\"[q] Quit.\")\n", " \n", " return input(\"What would you like to do? \")\n", "\n", "# Let us create a loop such that users can choose various options.\n", "\n", "names = [] # create a list to store names of existing friends\n", "selection = '' # initialize the selection\n", "while selection != 'q': \n", " display_title_bar()\n", " \n", " selection = get_user_selection()\n", " \n", " # Based on the user's selection, provide proper response\n", " if selection == '1':\n", " name = input (\"\\nEnter name of your new friend\")\n", " names.append(name)\n", " elif selection == '2':\n", " print(\"\\nYour existing friends are:\")\n", " for name in names:\n", " print(name.title())\n", " elif selection == 'q':\n", " print(\"\\nThanks for playing. Bye.\")\n", " else:\n", " print(\"\\nIllegal option !!\\n\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The use of \"Pickle\"\n", "You use *pickle* to store the state of the Python on disk such that \n", "we can get it back in its original form later. Let's illustrate." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Enable pickle so we can do data storage and retrieval\n", "import pickle\n", "\n", "# This program asks the user for some professors' names, and stores them.\n", "\n", "# Make an empty list to store new professor in.\n", "professors = []\n", "\n", "# Create a loop that lets users store new professors.\n", "new_professor = ''\n", "while new_professor != 'quit':\n", " print(\"\\nPlease tell me a new professor to remember.\")\n", " new_professor = input(\"Enter 'quit' to quit: \")\n", " if new_professor != 'quit':\n", " professors.append(new_professor)\n", "\n", "# Try to save the data to the file 'professors.pydata'.\n", "try:\n", " file_object = open('professors.pydata', 'wb') # create a file descriptor\n", " pickle.dump(professors, file_object) # write to the file pointed by the file descriptor\n", " file_object.close() # remember to close the file\n", " \n", " print(\"\\nI have remembered the following professors: \")\n", " for professor in professors:\n", " print(professor.title())\n", " \n", "except Exception as e:\n", " print(e)\n", " print(\"\\nI couldn't figure out how to store the professors list. Sorry.\")\n", " \n", "\n", "# Let us reset the professors list\n", "professors = []\n", "print(\"\\nThe professors list is now empty:\", professors)\n", "\n", "# Now let us try to open the file we created (and closed)\n", "\n", "try:\n", " file_object = open('professors.pydata', 'rb')\n", " professors = pickle.load(file_object)\n", " file_object.close()\n", "except:\n", " professors = []\n", "\n", "# Show the professors that are stored so far.\n", "if len(professors) > 0:\n", " print(\"The following professors are in stable storage: \")\n", " for professor in professors:\n", " print(professor.title())\n", "else:\n", " print(\"We have an empty professors list.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Description of the above program\n", "\n", "The above program introduces four **new** concepts:\n", "\n", "* A **try-except** block
\n", "         - A try-except block is used when you think a section of code might create an error. If an error occurs
\n", "             in a try block, the program does not end. Instead, program execution drops into the except block.
\n", "         - For the above program, we try to open a file to write out a list of professors.
\n", "         - If the file can not be opened for some reason, e.g., because the program doesn't have the permission
\n", "             to create a new file, then the program drops to the except block. In this case, we print the actual
\n", "             error message and a friendly message.
\n", "
\n", "* **Opening and closing files**
\n", "        - It tries to open the file 'professors.pydata'.
\n", "            -- The program uses the flag 'w' to tell Python to open the file for writing. The 'b' argument tells Python to write the file in bytes.
\n", "            -- If successful, the open file can be used through the file_object file descriptor.
\n", "            -- If the file does not yet exist, this line creates the file, in the same directory as the program.
\n", "        - Finally, it closes the file once we are finished working with it.
\n", "
\n", "* **A call to pickle.dump()**
\n", "        - Finally, it 'dumps' the list professors into the file that was opened. (*It is not dumped in a format that we can read.*)
\n", "
\n", "* **A call to pickle.load()**
\n", "        - We reset the professors list, then try to read it out again on stable storage via pickle.load(fd)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise\n", "Write a program to to ask the users to have the following options:\n", "* Input the names of friends he/she knows.\n", "* Display all names of his/her friends\n", "* Display the first 3 (or less) friends\n", "* Remove a friend from the list\n", "* Store the list in stable storage" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.3" } }, "nbformat": 4, "nbformat_minor": 2 }