Python 3 Read from Standard Input (stdin) Like C or Java

I will be using Python3 to read from standard input (or console). I will present two ways of doing this.

First Example

Input (data.txt)

First line of input will contain an integer which tells how many of lines (of data) will follow up. In each of the following lines, there will be one integer and and one floating-point (decimal) number, separated by a space:

3
1 2.3
3 4
5 6.0

Code (iotest.py)

if __name__ == '__main__':
    # Reading the first line and converting it to an integer
    num_entries = int(input())

    # Running a for loop to read each of the following lines
    for i in range(num_entries):
        current_line = input()
        # Getting the two values separated by space in variables `a` and `b`
        a, b = current_line.split()
        a, b = int(a), float(b)
        print(a, b)

Run the program

python3 iotest.py < data.txt

Second Example

Input (data.txt)

In this example, data file exactly looks like the one from first example, except that the first line is missing. Which means, we do not know how many data to read. We would have to run a while loop to read lines till there is and EoF (End of File) which tells us there is nothing more to read.

1 2.3
3 4
5 6.0

Code (iotest2.py)

if __name__ == '__main__':
    try:
        # Running a while loop since we don't know how many lines to read.
        while True:
            current_line = input()
            # Getting the two values separated by space in variables `a` and `b`
            a, b = current_line.split()
            a, b = int(a), float(b)
            print(a, b)
    except EOFError:
        # There is nothing more to do when we reach End of File (EOF)
        pass

Run

python3 iotest2.py < data.txt

Concluding Notes

  • You can run the programs without saving input data in a file. Just type python3 iotest.py and then enter data.
  • Be sure to use Python 3 only as the code will not work in Python 2
  • We are using input() built-in method of Python 3 which reads a single line and returns it as a string. So we have to convert them to appropriate data type (int/float).

Run Python script as CGI program with Apache2 in Linux / Wamp in Windows

If you’ve Apache & Python installed, you can execute your python scripts as CGI programs, which your visitors can access if you host the scripts in a server. You can write your scripts in python (file-name will end with .py) or in perl (extention .pl) or anything else which is compatible.

Step 1 – Write a “Hello, World! ” script in Python

In a text editor, type following code. Give the file name “first.py

#!/usr/bin/env python
print "Content-type: text/html\n"

print "Hello, world!"

The first line is important – it tells where in our computer Python is available. If you’re using windows, use appropriate location, for example, change the first line to something like:

#!C:/Python27/python.exe

Step 2 – Put the script in a suitable directory

Important: If you are in Linux, make your file executable! Type:

chmod +x /path/to/your/first.py

Pretty simple!

  1. Let’s rename the file to first.py and make it executable, if we’re in Linux.
  2. Put it in a directory named “cgi-bin” under our document root. Then, the file may be accessed in the web-browser by simply typing: http://localhost/cgi-bin/first.py

Step 3 – Configure Apache2

Next step is to configure Apache so that it treats our file as a CGI program. Go to the directory where your Apache configuration file exists. In Linux, it resides under /etc/apache2/ and the configuration file is httpd.conf

NOTE: If virtual hosts are enabled (normally the are enabled), changing the httpd.conf will have no effect. You may need to edit particular configuration file for the site which is enabled. Go to the sites-enabled  directory and open the file which is currently enabled (If you have only the file “default” in your /etc/apache2/sites-enabled directory, you should open this file with your text editor)

NOTE: If you are in windows, and using Wamp, you can simply open the httpd.conf file and make following changes.

Edit the configuration file:

Search for the line: ScriptAlias /cgi-bin/ /whatever-path/ – when you find it, comment out the line: that is add a # in front of the line:

#ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/

Then,  paste following lines of code:

<Directory "/location/to/your/cgi-bin/">
AddHandler cgi-script .cgi .py
AllowOverride All
Options +Indexes FollowSymLinks +ExecCGI
Order allow,deny
Allow from all
</Directory>

If your first.py is in /var/www/cgi-bin/ folder, then replace the first line by <Directory “/var/www/cgi-bin”>

You’re done! Now restart Apache to activate all changes.

If you’re in Linux, open a terminal and enter sudo /etc/init.d/apache2 reload to restart Apache. If you’re using Wamp in Windows, you can restart Apache clicking appropriate icons!

 

Test…

 

Fire up your web browser, type http://localhost/cgi-bin/first.py and hit Enter…

 

If you find only the text:

Hello, world!

in the page, then congratulations!

If you find any other text than Hello, world!, something went wrong. Check for your mistakes. Ensure that “cgi_module” Apache module is enabled.

 

You may find this link helpful.

Python MySQLdb equivalent for PHP’s mysql_insert_id()

What you’re looking for is lastrowid property of a cursor object.

Code:

import MySQLdb # MySQLdb module must be installed on the system
connection = MySQLdb.connect(...) # Details skipped
cursor = connection.cursor()
query = "INSERT INTO ... " # put query here
cursor.execute(query)
print cursor.lastrowid # BINGO! This will print the id (auto-increment column) of the last inserted row
# Other codes here

Thanks to this article on the Internet

C style For loop in Python

A for loop in C/C++/PHP/Java Or many well-known programming language will appear as:

int loopStartVariable = 0;
int loopEndVariable = 5;
for(i=loopStartVariable; i < loopEndVariable; i++){
	// do something with i
}

Python has no C-style for loop, which is has is for in loop like foreach loop available in PHP.

To achive the same goal as the code snippet written in C above, we may write following code in python:

loopStartVariable = 0;
loopEndVariable = 5;
for i in range(loopStartVariable, loopEndVariable):
	# Do something with i
print "loop ends here"

Python Tutorial: Dictionaries (Key-value pair Maps) Basics

Dictionary in Python is a data-structure also known as map. Chances are you’re already familiar with them, if using Associative Arrays in PHP or Hashtables in C++ or Java. You may imagine a dictionary as an array, where instead of numerical indexes (the first element of array is indexed as 0, the second element is indexed by 1 and so on), you use string indexes. Each element of a map is accessed (or, indexed) by an unique “key”; so they are also known as key-value pairs. Dictionaries are not sequences, so the order in which elements are added to the dictionary doesn’t matter.

Example

Suppose, we want a data-structure to store information about a cooking recipe. For the recipe, we want to store which food (dish) we’re cooking, how many quantities it serve, and the color of the food being  prepared (don’t ask me why).

You can create a map using this syntax: variable_name = {key:value}

In the following examples, any text after “>>>” is actual code that you use in your Python scripts. You can also type this code in Python command line interpreter. Any line not beginning with “>>>” indicates an output of the previous code.

Code:
>>> D = {'food': 'pudding', 'quantity': 4, 'color': 'pink'}

>>> D['food'] # Fetch value of key 'food'
'pudding'

>>> D['quantity'] += 1 # Add 1 to 'quantity' value

>>> D
{'food': 'pudding', 'color': 'pink', 'quantity': 5}

Alternately, you can create an empty map, and insert key-value pairs later. Unlike Lists (arrays in Python), you can perform out-of-bound assignments:

Code:
>>> D = {}

>>> D['name'] = 'Bob' # Insert element on-the-fly

>>> D['job'] = 'dev'

>>> D['age'] = 4

>>> D
{'age': 4, 'job': 'dev', 'name': 'Bob'}

>>> print D['name']
Bob

Nesting

Like lists, nesting is also possible in maps. Consider the following code pattern:

Code:
>>> rec = {'name': {'first': 'Bob', 'last': 'Smith'},
                  'job': ['dev', 'mgr'],
                  'age': 40.5}

>>> rec['name'] # 'Name' is a nested dictionary
{'last': 'Smith', 'first': 'Bob'}

>>> rec['name']['last'] # Index the nested dictionary
'Smith'

>>> rec['job'] # 'Job' is a nested list
['dev', 'mgr']

>>> rec['job'][-1] # Index the nested list
'mgr'

>>> rec['job'].append('janitor') # Expand Bob's job description in-place

>>> rec
{'age': 40.5, 'job': ['dev', 'mgr', 'janitor'], 'name': {'last': 'Smith', 'first':
'Bob'}}