Categories
Python Study Notes

Pausing Python Code

While working on my first web scraping program in Python3, I wanted to pause between each pull from the target site. Here is an example of how to pause Python code mid-execution:

import random
import time

count = 0
while count < 5 :
    print("On loop number ",count," at ",
           time.strftime("%H:%M:%S",time.localtime()))
    time.sleep(10 + random.randint(10,30))
    count += 1
print("fin")

Here is an alternate form for accessing the random and time libraries:

from random import randint
from time import sleep, localtime, strftime

count = 0
while count < 5 :
    print("On loop number ",count," at ",
           strftime("%H:%M:%S", localtime()))
    sleep(10 + randint(10,30))
    count += 1
print("fin")

Both of these forms produce the same output:

On loop number 0 at 21:12:55
On loop number 1 at 21:13:28
On loop number 2 at 21:14:07
On loop number 3 at 21:14:34
On loop number 4 at 21:15:11
fin

These examples show two different ways to bind (or name) the library (or module) within the current code. The first approach binds the library by the name of the library. To use any method in the library, both the library and the method must be specified using dot notation (for example, ‘random.randint()’). In the second form, using ‘from…import,’ the parts are bound (or named) directly, so no library name is required (for example, ‘randint()’). The following examples show the kind of error that comes up if the two are confused:

import time
print("Not going to give me the ", 
       strftime("%H:%M:%S", localtime()))
NameError Traceback (most recent call last) 
<ipython-input-1-1311e7eb4821> in <module> 
      1 import time 
----> 2 print("Not going to give me the ", 
               strftime("  %H:%M:%S", localtime()))
NameError: name 'strftime' is not defined
from time import strftime,localtime
print("Not going to give me the ",
       time.strftime("%H:%M:%S", time.localtime()))
NameError Traceback (most recent call last)
<ipython-input-1-e7ef42e5203c> in <module>
      1 from time import strftime,localtime
----> 2 print("Not going to give me the ",
               time.strftime("%H:%M:%S", time.localtime()))
NameError: name 'time' is not defined

While using ‘from’ may mean less typing, it can also cause confusion if the same name is used by different libraries or objects in a section of code. A compromise is to give the library a nickname like so:

import time as T
print("Going to give me the ",
       T.strftime("%H:%M:%S", T.localtime()))
Going to give me the 21:39:31

This clarifies where localtime() comes from, yet saves a bit of typing.

Leave a Reply

Your email address will not be published. Required fields are marked *