Friday, 20 January 2017

Python Interpreter: Writing functions

In my previous post, I shared about how to get help from the Python interpreter.

Today, let's learn more about the Python interpreter by writing functions.

We are going to write a Python function to run a periodic task.

First, our periodic task is a function to print the current time:

def printTime():
  print(time.asctime())


Continuation Lines

You may have noticed that the printTime() function consisted of 2 lines, and may ask how to input the second line into the interpreter.

The answer is that the interpreter knows that you are going to need a second line of input when it sees the colon sign(":"). So the interpreter will automatically give a "continuation line prompt" (shown by the 3 dots "..."). In the continuation line, you can key-in " print(time.asctime())". 

When you are done and you don't want any more continuation lines, just hit "Return" until you get back the normal Python prompt as shown below. 

>>> def printTime():
...   print(time.asctime())
...

Continuation lines work for if-then-else and other Python control flow structures as well.
Once in a while, you may need a continuation line outside of functions/control flow. For these situations, just key-in the backslash character ‘\’ to get the continuation line prompt.

Next, how do we schedule a periodic task?
Googling lead me to the following code that I am not familiar with:

1
2
3
4
5
6
7
8
import sched, time
s = sched.scheduler(time.time, time.sleep)

def periodic(scheduler, interval, action, actionargs=()):
  scheduler.enter(interval, 1, periodic, (scheduler, interval, action, actionargs))
  action(*actionargs)

periodic(s, 5, printTime)

In particular, I do not know what is the meaning of s object at line 2.
Furthermore, when I run the code, the time was printed only once, instead of periodically with an interval of 5 seconds (as expected from line 8).
To solve this, I will use the interpreter as shown in the next section.

Finding Out The Type

Here is what I will key-in to the interpreter:

>>> print(type(s))
<class 'sched.scheduler'>

The interpreter reveals that it is a sched.scheduler object.

Reading the help for the scheduler class led me to a method called "run()". Will this method kick start the periodic tasks?

We can find out quickly with the interpreter by entering the following line
>>> s.run()


It works!

As you can see, the interpreter allowed me to experiment and find out how to kick-start the scheduler. This is certainly more flexible and faster than the "edit-compile-test" cycle, which I had discussed in an earlier post.

Explanation of Scheduler Object

For those who would like to understand how a scheduler is used to implement a periodic task, the trick is to have the task re-schedule itself at the specified interval. This is done at line 5.

No comments:

Post a Comment