Simple way to create png image with an input text.


First you need to have the PIL python module and import this.
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from PIL import ImageFilter
Next will be this function.Basically will make and return one RGBA image data type.
def make_img(image, textColor, backgroundColor):
  img = image.convert("RGBA")
  img.putdata([textColor if value == 0 else backgroundColor 
                   for value in image.getdata()])
  return img
The next step is to set the text , font and the new image.
I use Arggotsc.ttf. You can use any TrueType font.
text = " Inca un script in python! "
font = ImageFont.truetype('Arggotsc.ttf', 55)
image = Image.new("1", font.getsize(text), '#FFF')
Now we can draw, add text, resize, bur the text and finally save the image.
draw = ImageDraw.Draw(image)
draw.text((0, 0), text, font=font)
image = image.resize([i for i in image.size], Image.NEAREST)
imgText = make_img(image, (200, 200, 200), (0, 0, 0, 0))
blur_img = make_img(image, (0, 0, 0), (0, 0, 0, 0))
for i in range(3): 
  blur_img = blur_img.filter(ImageFilter.BLUR)
blur_img.paste(imgText, (0, 0), imgText)
blur_img.save("text-img.png")
The result is:

How to deal with environment variables using python script



Any OS like Linux, Unix, Windows has environment variables.
Also any variables which must not be committed on a public code can be used in this way.
You can give this variables to your application.
Let's see one simple example about how to do that:
import os
ENV_VAR = os.environ.get("ENV_VAR", None)
if not ENV_VAR:
        print "not ENV_VAR"
if ENV_VAR:
        print "yes ! is ENV_VAR"
Now you can give this ENV_VAR to the script or not. See next...
usertest@home:~$ ENV_VAR=true python demo-env.py 
yes ! is ENV_VAR
usertest@home:~$ python demo-env.py 
not ENV_VAR
With Python 3 on Unix, environment variables are decoded using the file system encoding.

A Brief History of Python

A Brief History of Pytho:

The development of Python occurred at a time when many other dynamic (and open-source) programming languages such as Tcl, Perl, and (much later) Ruby were also being actively developed and gaining popularity. To help put Python in its proper historical perspective, the following list shows the release history of Python. The earliest dates are approximate as I didn't consistently record all events:


Release DateVersion
December, 1989Implementation started
1990Internal releases at CWI
February 20, 19910.9.0 (released to alt.sources)
February, 19910.9.1
Autumn, 19910.9.2
December 24, 19910.9.4
January 2, 19920.9.5 (Macintosh only)
April 6, 19920.9.6
Unknown, 19920.9.7beta
January 9, 19930.9.8
July 29, 19930.9.9
January 26, 19941.0.0
February 15, 19941.0.2
May 4, 19941.0.3
July 14, 19941.0.4
October 11, 19941.1
November 10, 19941.1.1
April 13, 19951.2
October 13, 19951.3
October 25, 19961.4
January 3, 19981.5
October 31, 19981.5.1
April 13, 19991.5.2
September 5, 20001.6
October 16, 20002.0
April 17, 20012.1
December 21, 20012.2
July 29, 20032.3
November 30, 20042.4
September 16, 20062.5
October 1, 20082.6
December 3, 20083.0
I've added hyperlinks to the releases that are still being advertised on python.org at this time. Note that many releases were followed by several micro-releases, e.g. 2.0.1; I haven't bothered to include these in the table as otherwise it would become too long. Source tarball of very old releases are also still accessible, here: http://www.python.org/ftp/python/src/. Various ancient binary releases and other historical artefacts can still be found by going one level up from there.

Python's Design Philosophy

Python's Design Philosophy


First of all, Python was originally conceived as a one-person “skunkworks” project – there was no official budget, and I wanted results quickly, in part so that I could convince management to support the project (in which I was fairly successful). This led to a number of timesaving rules:
  • Borrow ideas from elsewhere whenever it makes sense.
  • “Things should be as simple as possible, but no simpler.” (Einstein)
  • Do one thing well (The "UNIX philosophy").
  • Don’t fret too much about performance--plan to optimize later when needed.
  • Don’t fight the environment and go with the flow.
  • Don’t try for perfection because “good enough” is often just that.
  • (Hence) it’s okay to cut corners sometimes, especially if you can do it right later.
Other principles weren’t intended as timesavers. Sometimes they were quite the opposite:
  • The Python implementation should not be tied to a particular platform. It’s okay if some functionality is not always available, but the core should work everywhere.
  • Don’t bother users with details that the machine can handle (I didn’t always follow this rule and some of the of the disastrous consequences are described in later sections).
  • Support and encourage platform-independent user code, but don’t cut off access to platform capabilities or properties (This is in sharp contrast to Java.)
  • A large complex system should have multiple levels of extensibility. This maximizes the opportunities for users, sophisticated or not, to help themselves.
  • Errors should not be fatal. That is, user code should be able to recover from error conditions as long as the virtual machine is still functional.
  • At the same time, errors should not pass silently (These last two items naturally led to the decision to use exceptions throughout the implementation.)
  • A bug in the user’s Python code should not be allowed to lead to undefined behavior of the Python interpreter; a core dump is never the user’s fault.
Finally, I had various ideas about good programming language design, which were largely imprinted on me by the ABC group where I had my first real experience with language implementation and design. These ideas are the hardest to put into words, as they mostly revolved around subjective concepts like elegance, simplicity and readability.

Although I will discuss more of ABC's influence on Python a little later, I’d like to mention one readability rule specifically: punctuation characters should be used conservatively, in line with their common use in written English or high-school algebra. Exceptions are made when a particular notation is a long-standing tradition in programming languages, such as “x*y” for multiplication, “a[i]” for array subscription, or “x.foo” for attribute selection, but Python does not use “$” to indicate variables, nor “!” to indicate operations with side effects.

Tim Peters, a long time Python user who eventually became its most prolific and tenacious core developer, attempted to capture my unstated design principles in what he calls the “Zen of Python.” I quote it here in its entirety:
  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Complex is better than complicated.
  • Flat is better than nested.
  • Sparse is better than dense.
  • Readability counts.
  • Special cases aren't special enough to break the rules.
  • Although practicality beats purity.
  • Errors should never pass silently.
  • Unless explicitly silenced.
  • In the face of ambiguity, refuse the temptation to guess.
  • There should be one-- and preferably only one --obvious way to do it.
  • Although that way may not be obvious at first unless you're Dutch.
  • Now is better than never.
  • Although never is often better than right now.
  • If the implementation is hard to explain, it's a bad idea.
  • If the implementation is easy to explain, it may be a good idea.
  • Namespaces are one honking great idea -- let's do more of those!
Although my experience with ABC greatly influenced Python, the ABC group had a few design principles that were radically different from Python’s. In many ways, Python is a conscious departure from these:

  • The ABC group strived for perfection. For example, they used tree-based data structure algorithms that were proven to be optimal for asymptotically large collections (but were not so great for small collections).
  • The ABC group wanted to isolate the user, as completely as possible, from the “big, bad world of computers” out there. Not only should there be no limit on the range of numbers, the length of strings, or the size of collections (other than the total memory available), but users should also not be required to deal with files, disks, “saving”, or other programs. ABC should be the only tool they ever needed. This desire also caused the ABC group to create a complete integrated editing environment, unique to ABC (There was an escape possible from ABC’s environment, for sure, but it was mostly an afterthought, and not accessible directly from the language.)
  • The ABC group assumed that the users had no prior computer experience (or were willing to forget it). Thus, alternative terminology was introduced that was considered more “newbie-friendly” than standard programming terms. For example, procedures were called “how-tos” and variables “locations”.
  • The ABC group designed ABC without an evolutionary path in mind, and without expecting user participation in the design of the language. ABC was created as a closed system, as flawless as its designers could make it. Users were not encouraged to “look under the hood”. Although there was talk of opening up parts of the implementation to advanced users in later stages of the project, this was never realized.
In many ways, the design philosophy I used when creating Python is probably one of the main reasons for its ultimate success. Rather than striving for perfection, early adopters found that Python worked "well enough" for their purposes. As the user-base grew, suggestions for improvement were gradually incorporated into the language. As we will seen in later sections, many of these improvements have involved substantial changes and reworking of core parts of the language. Even today, Python continues to evolve.

Python projects

Python projects

Python serves as an umbrella organization for around a dozen open source Python projects each year. This year, the following projects are participating:

  • CPython : core Python and the standard library
  • GNU Mailman: the ubiquitous mailing list package
  • Mercurial: a distributed source control management tool 
  • BinPy: a platform for building circuit-based applications or logical games
  • Vispy: high-performance interactive visualizations
  • TARDIS-SN: supernova radiative transfer in Python
  • SunPy: Python for solar physics
  • Scrapy: a fast, high-level screen scraping and web crawling framework
  • Theano: an optimizing compiler for numpy.ndarray and scipy.sparse matrix
  • Kivy: a library for making cross-platform, multi-touch apps
  • MNE-Python: a software package for processing MEG and EEG data
  • scikit-image: a collection of algorithms for image processing
  • scikit-learn: a Python module for machine learning
  • PyDy: a package for studying multibody dynamics with Python
  • SciPy and NumPy: open-source software for mathematics, science, and engineering
  • AstroPy: a community Python library for astronomy

Fixing Reeborg

Fixing Reeborg:

For those familiar with rur-ple lessons, I thought I would share the first draft of my introduction to classes. Some points to remember from preceding lessons:
  • I used the analogy of synonyms to talk about variables
  • Students have already seen how to define new object [like Reeborg = UsedRobot()]
I definitely welcome comments!

Fixing up Reeborg

As we have seen, we can create new robots by using the notation
Reeborg = UsedRobot()
Erdna = UsedRobot(2, 2)
However, these robots are just like the original nameless one: they
can only turn left. To teach them how to turn right, we could define
a function similar to what we did before:
def Reeborg_turn_right():
 for i in range(3):
     Reeborg.turn_left()
However, there are at least two problems with this approach:
  • We need to define a similar function for every single robot we create (Reeborg, Erdna, ...).
  • Reeborg and turn are separated by an underscore character "_" for the function we defined [to turn right] and by a dot "." for the built-in method [to turn left]. This would not look right...
A better approach is to define a new class that would inherit from the class UsedRobot. This is
what we do in the next section.
Designing a new class
I will show you first how we can fix our robot so that it knows how to turn right, and explain what I did afterwords.
class RepairedRobot(UsedRobot):
 def turn_right(synonym_used_to_refer_to_this_object):
     for i in range(3):
         synonym_used_to_refer_to_this_object.turn_left()
Here's how we can then use this new class of objects:
newReeborg = RepairedRobot()
newErdna = RepairedRobot(2, 2)

newReeborg.turn_left()    # as before
newReeborg.turn_right()   # new method!

newErdna.turn_right()     # this one works too!
And now, it is time to explain. The Python keyword class indicates that we are going to define a new type of "function", one that creates objects. What follows class is: RepairedRobot(UsedRobot).

RepairedRobot is the name of our new class; by writing UsedRobot between the parentheses, we ensure that the new class RepairedRobot inherits all the methods and attributes that UsedRobot had. Thus, when we write:
newReeborg = RepairedRobot()
we create a new robot "named" newReeborg which can do (at least all) the same things that the old Reeborg = UsedRobot() could do.
Next, inside the new class, as indicated by the indented block, we define a new method, turn_right(). By defining it inside the class, we take the first step to insure that all the robots that are created by calling RepairedRobot() will be able to turn right!
The second step that is required is to tell Python that the method will "belong" to the particular object that has been created. To do so, we use the variable synonym_used_to_refer_to_this_object which will refer to newReeborg, newErdna, etc., depending on what object is created. When we write
newReeborg = RepairedRobot()
Python creates a new instance of the class RepairedRobot and defines all the methods, replacing the first argument of the method (synonym_used_to_refer_to_this_object) by the name of the
instance (newReeborg).
Now, synonym_used_to_refer_to_this_object is rather a long name to type. By convention, another variable name is used: self. Thus, to follow the normal convention, I should have
written:
class RepairedRobot(UsedRobot):
 def turn_right(self):
     for i in range(3):
         self.turn_left()