Windows Idle Python – two confusing screens

Using the two screens in python idle for windows and ubuntu

When using the Python Idle editor and run environment, users are sometimes confused with two completely separate windows, or get one window which interprets Python but does not allow them to save their work.

Python Shell Window

The primary Python screen is the Python shell. If that is your only window, you should select File->New Window.

Untitled (maybe)

This window is a seperate editor task. This is where you edit entire programs.

The Rhythm

For short little things, you can execute them in the shell. Try these and see if you get the same output.

print x


print x.find('12'),x.find('23'),x.find('asdf')

0 1 -1

if x.find('23')>-1:
  print x.index('23')



sudo apt install python-celery-common

all configuration to run the celery process is put in a python file sometimes called

celery -A tasks worker –loglevel=info

But you might have multiple workers named and so you would start them in two separate shells using

celery -A worker1 worker –loglevel=info
celery -A worker2 worker –loglevel=info

The “functions” you are going to background will be in worker1 or worker2.

Curling, just not Canadian Style Python 2.6.6 and the urllib2 library

In bash, getting a web page

curl >html.html

The bash curl command has nothing to do with Canadian Curling, which is like shuffleboard on ice amidst the tension garnered tolerating a joke about the Queen or the national health care system from a surfboard riding processed cheese eating upper Mexican from south of the barbarian line. In bash, curl is short for client url, a simple http request of a web address.

In Python

x = urllib2.urlopen("")
w =

And as a part of a class init

  def __init__(self,TableName,filename,url):
    self.sqhandle=sqlite3.connect(filename) # empty if noexist
    self.sq1cursor = self.sqhandle.cursor()
    self.filename = filename
      self.sq1cursor.execute('''CREATE TABLE '''
         +TableName+''' (somenum real, somestring text)''')
      print TableName,"table already exists"
    self.samples = 0
    x = urllib2.urlopen(url)
    self.pagedata =

So if we instantiate a class we now have the html as classname.pagedata and sqlite3 handle and cursor as classname.sqhandle and sq1cursor

We need to do some things with sql like

    command = 'INSERT INTO '+table+' VALUES (' + x +', "'+ y +'")'
      print command

sqlite3 insert a row

  def sqlinsert(sqhandle,sq1cursor,table,x,y):
    command = 'INSERT INTO '+table+' VALUES (' + x +', "'+ y +'")'
      print "failed to ", command

Perl MySql Example

Perl with DBI, Perl Database access

!/usr/bin/perl -w


script to add up some table data

use DBI;
use CGI::Carp qw(fatalsToBrowser);

print “Content-type: text/html\n\n”;
my $dbh = DBI->connect(’dbi:mysql:database=DATABASE_NAME;host=localhost’, ‘USERNAME’, ‘PASSWORD’)
or die “Couldn’t connect to database: ” . DBI->errstr;

my ( $k, $id, $book_date, $svc_type, $cust_id, $time_pref, $a_sched,$a_eight);
my $t_date=”20080115″;

$sqlquery = qq( SELECT id, book_date, svc_type, cust_id, time_pref, FROM orders WHERE  move_date = $t_date );
$sth = $dbh->prepare ( $sqlquery );
$sth->execute() || die “Couldn’t execute query: ” . DBI->errstr;

$k = 0;
$sth->bind_columns( \$id, \$book_date, \$svc_type, \$cust_id, \$move_date, \$time_pref, \$est_men, \$est_trks );
while ( $sth->fetch() ) {
$a_sched  += 1;
if ( $time_pref eq “8-9A.M.” ) { $a_eight  +=1; }

Now $a_sched contains the number of records $a_eight contains the number of 8-9A.M. record for that date.

atlanta custom database design   vehicle dispatch ERP

What is the difference between parenthesis and brackets in Python

Tuples and lists

Both are arrays, but tuples are immutable. This means that once you define a tuple, you cannot add elements, pop, append, remove an element, etc. You need to create a new tuple out of the old one every time you make a change.

  • Tuples (1,2,3,4,5,6) are great for static definition. They are hashable, lean and unequivocal.
  • Lists [1,2,3,4,5,6] are great for computation. They are mutable and queueable.

Both are addressed with integers in brackets.

Whether it is a list or a tuple, addressing one element is the same.

create a tuple with y = (“a”,”b”,”c”) and do this;

y = ("a","b","c")
print (y[0])
for i in y:
    print (i)

For lists and tuples, know this too;

for i in range(0,len(y)):
    print (i,y,y[i])

Now redefine y as a list and try it again. Same results?

Python Mysql multi handle 2.7.2

Real world use case for multiple instantiations of python classes, Use a Python Class more than once

At the beginning of our python program, we normally would import the library for MySql operations;

import MySQLdb

Using this library, we then use .connect() and .cursor but because we may be using the same database repeatedly, here is an alternate method of initializing our connection. First, we create a file called in our working directory to initialize the database connection;

import MySQLdb
def dbconn():
  server = 'localhost'
  user = 'MySql_user_name'
  password = 'MySql_password'
  dbase = 'MySql_database_name'
  return MySQLdb.connect(server,user,password,dbase)

This means that I can quickly connect to the same database, everytime I write a new Python program, substituting the new library for making the connection.

import credentials
handle = credentials.dbconn();

We now can look at some table rows with only four more statements;

sql="SELECT * FROM table_name WHERE 1=1"

Add on more statement, like ‘print rowArray’ or do whatever you need to do to look at the row. You probably will write a loop that encloses the last statement.

Just to take another approach, let’s look at our MySql Python connect without the separate credentials function;

import MySQLdb
server = 'localhost'
user = 'MySql_user_name'
password = 'MySql_password'
dbase = 'MySql_database_name'
handle = MySQLdb.connect(server,user,password,dbase)

sql="SELECT * FROM table_name WHERE 1=1"

print rowArray

And with the credentials library;

import credentials
sql="SELECT * FROM table_name WHERE 1=1"

print rowArray

Next an example using your to make a python program to read two tables,first we get the user record, and then their posts.

import credentials
uSql="SELECT * FROM jos_users WHERE id=57"
cSql="SELECT * FROM jos_content WHERE created_by=57"
for i in cCursor.fetchone
  print i['title']

python string split example 2.7.2

6 lines of code, no modules to import

x = 'joe fred terry mitch jane betty mary ellen'
while (1==1):
    y = x.find(" ")
    if y==-1: break
    print 'next name ',x[:y]
    x = x[y+1:]

3 lines of code, using the string module. Elegant because the loop definition is overt and evident.

import string

x = 'joe fred terry mitch jane betty mary ellen'
for name in string.split(x):
  print 'next name ',name

Other Examples

  1. split a semicolon delimitted string, or any delimiter in a string of fields
  2. some string library in python constants
  3. search a string (you don’t need the string library), i.e. ‘pos’ or
import string

x = 'joe;fred;terry;mitch;jane;betty;mary;ellen'
for name in string.split(x,';'):
  print 'next name ',name

import string

print "1..",string.printable
print "2..",string.uppercase
print "3..",string.letters
print "4..",string.digits
print "5..",string.punctuation

print x.index('john')
# this yields the integer '4'
print x[4:]
# this would print john, or the rest of the string which is here john