How Do You Get Python to Compute How Long Something Took?

Problem scenario
You want to check the runtime duration of a section of Python code. How do you compute the amount of time something took in Python?

Solution
Write a program like this:

import datetime, time
t1 = datetime.datetime.now()
time.sleep(5) # replace this line with the section of code you want to time
t2 = datetime.datetime.now()
t3 = t2 – t1
print(“Time format is in hours:minutes:seconds:seconds_decimals”)
print(t3)  » Read more..

In Python, How Do You Call a Bound Function as a New Thread with the thread Module?

Problem scenario
You want to write a program to call a bound function in a new thread. How do you do this?

Solution
Run this program (e.g., python foobar.py):

import _thread as thread
class mighty:
def cool():
print(“Cool.”)
def contint():
print(“Hello!”)
if name == “main”:
foobar = thread.start_new_thread(mighty.cool, () )
print(“thread finished…exiting”)

 » Read more..

In Python, How Do You Call an Unbound Function as a New Thread with the threading Module?

Problem scenario
You want to write a program to call a unbound function in a new thread with the threading module. How do you do this?

Solution
Run this program (e.g., python foobar.py):

from threading import Thread
def contint():
print(“Hello!”) if name == “main”:
thread = Thread(contint())
thread.start()
thread.join()
print(“thread finished…exiting”)  » Read more..

How Do You Get a PHP Program to Invoke a Python Program via Browsing a Website?

Problem scenario
You want Debian/Ubuntu Linux to support a website. You want a Python program to run every time a web page is downloaded. How do you get a PHP program to invoke a Python program on Debian/Ubuntu Linux?

Solution

Prerequisites
i. This assumes you have Apache2 and PHP installed. If you need assistance run this: sudo apt -y install apache2 php
ii.

 » Read more..

How Do You Troubleshoot an Error Such as “UnboundLocalError: local variable ‘foobar’ referenced before assignment”?

Problem scenario
You run a Python program. You receive this message: “UnboundLocalError: local variable ‘foobar’ referenced before assignment”

What should you do?

Solution
Initialize the variable (e.g., foobar = 0). If you do so inside a function wherein foobar, that may work. If you want it to be available globally throughout your program, you will initialize it outside of a function.

 » Read more..

How Do You Write a Python Program to Create New Processes with the multiprocessing Library?

Problem scenario
You want to create new processes with the multiprocessing library in Python. What should you do?

Solution
Run this program:

“”” In a duplicate terminal window, run this command before, during and after you run the pyhon script: sudo ps -ef | grep python | wc -l

The integer that returns will go up by two showing a new processes have been created when the program is still running.  » Read more..

How Do You Write a Python Program to Test If Two Words Are Anagrams?

Problem scenario
You want a program to test if two words are anagramous with each other. You want the test to be case insensitive. How do you write a program that will interactively prompt the user for two different words and test if they are anagrams?

Solution
Use this Python 3 program (and it will interactively prompt you to enter two words):

word1 = input(“Enter one word: “).lower()
word2 = input(“Enter a second word: “).lower()

wL1 = list(word1)
wL2 = list(word2)

wL1.sort()
wL2.sort()

if (wL1 == wL2):
print(“The two programs are anagrams!”)
else:
print(“The two words are NOT anagrams!”)

It will not work with Python 2.

 » Read more..

In Python Are Dictionaries Much Slower in Performance Compared to Lists or Tuples?

Problem scenario
You want to know how dictionaries perform as iterables in Python. In Python for printing the values of every key-value pair in a dictionary, is it faster or slower than printing every item in a list? How does it compare to a tuple?

Solution
For this example we use integer keys in the dictionary. Keys can be strings or other objects.

 » Read more..

How Do You Upgrade to Python 3.x on Ubuntu 16?

Problem scenario
You are using Python 2.7.12 on Ubuntu 16. You want to upgrade to Python 3.x You are having problems. You tried several things as follows:
sudo apt-get -y install python 3.7
But you see this:

python is already the newest version (2.7.12-1~16.04).
python set to manually installed.
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.

 » Read more..

How Do You Write a Python Program to Accept Input in a Non-interactive Way at Run-time?

Problem scenario
You are used to using “input” with Python 3 to prompt the user for a value. How do you pass input when you execute a Python program?

Solution
1. Use import sys

2. Use sys.argv[1] to refer to the first argument passed when you run your program like this:

python3 goodprog.py foo

The program will see “sys.argv[1]” as the string foo.

 » Read more..