Thursday, March 31, 2016

Flask : using python flask

http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
http://flask.pocoo.org/docs/0.10/quickstart/
https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-14-04
http://stackoverflow.com/questions/16344756/auto-reloading-python-flask-app-upon-code-changes
http://www.tutorialspoint.com/flask/flask_file_uploading.htm


Note:
-for a route, always the first function after the route declaration is called, no matter how many router and how many functions are together.

Minimum app is:   (6-lines of code)

- Create file: any_file.py

from flask import Flask
app = Flask(__name__)
@app.route("/")
def any_function():
    return 'Hello World!'
app.run()   # put debug = True : for auto reload of updated script as: app.run(debug = True)

# Run Flask server: python any_file.py   # Runs the server on localhost at default port 5000

# Program flow:

- when app.run is called, a running web server is setup
-When the local host is contacted by any browser on the above port, data stream is directed to the Flask framework that in turn directs to the flask calling file; any_file.py (in this case)
-The function just next to the called route is called.

Monday, March 28, 2016

number literals in python: hex, octal, and binary

http://stackoverflow.com/questions/1476/how-do-you-express-binary-literals-in-python

hex:   0x11 : using 0x
octal: 011  : starting with 0
binary: 0b11 : starting with 0b

print 0x11   => 11
print 011   => 9
print 0b11   => 3

Tuesday, March 22, 2016

file size in python

os.path.getsize(path)

json in python

http://docs.python-guide.org/en/latest/scenarios/json/

-json library is simple: A. converts python dictionary to json string, B. json string to python dictionary

-two importand methods: A. loads(json_string) to create regular python dictionary, B. dumps(python_dictionary)

-difference between json string and python dictionary: They are very similar. json string is a standard JavaScript Object Notation string which must include the outer curly braces as part of the string. In python dictionary the outer curly braces are reserved python keyword:

Example:

python dictionary: {'age':12}
json string            : '{'age':12}'

Only difference: single quote around python dictionary in json string
Though only difference is, the quote - json is universal format, but json type dictionary is python specific.

Internal mechanism: conversion between json and dictionary:



Note: if you find 'u' in json string - this only means the content is unicode




 

u in python json string

http://stackoverflow.com/questions/13940272/python-json-loads-returns-items-prefixing-with-u


u => unicode

create read binary file in python

python bytes:
http://www.dotnetperls.com/bytes-python

Note:
1. file pointer always reads and writes strings (byte string and text string), NOT numbers
2. generally binary flag for open does not work properly - not needed
3. to convert the read bytes to hex string, use: .encode('hex')
Example: open('test.txt', 'r').read().encode('hex')
4. to write binary: create a byte string, then write that string: Example: str = '\x03\x04'
    open('test.txt', 'w').write('\x29')

kill process

http://stackoverflow.com/questions/2940858/kill-process-by-name-in-python

>>> import subprocess, signal
>>> p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
>>> out, err = p.communicate()
gives you ps -A's output in the out variable (a string). You can break it down into lines and loop on them...:
>>> for line in out.splitlines():
...   if 'iChat' in line:
...     pid = int(line.split(None, 1)[0])
...     os.kill(pid, signal.SIGKILL)
... 

list imported modules

http://stackoverflow.com/questions/4858100/how-to-list-imported-modules
sys.modules.keys()​​​

launch program from python console

http://stackoverflow.com/questions/204017/how-do-i-execute-a-program-from-python-os-system-fails-due-to-spaces-in-path

# Call without argument
>>> import os
>>> os.system('jeex')

# call with argument
subprocess.call(['jeex', 'test.txt'])


list directory contents from python script or console

http://stackoverflow.com/questions/11968976/list-files-in-only-the-current-directory

>>> print os.listdir(os.curdir)
['test.txt', 'output.mid', 'midi_1.py', '_midi_1.py', 'song.txt', 'output_test.mid']


>>> print os.listdir('.')
['test.txt', 'output.mid', 'midi_1.py', '_midi_1.py', 'song.txt', 'output_test.mid']

>>> print os.listdir('./')
['test.txt', 'output.mid', 'midi_1.py', '_midi_1.py', 'song.txt', 'output_test.mid']

read write binary data

https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch05s04.html

byte string vs text string

python ord (ordinal)

http://www.linuxnix.com/pfotd-python-ord-function-examples/

-Coverts symbol to number

Thursday, March 17, 2016

python run command with subprocess communicate

http://stackoverflow.com/questions/8077868/python-subprocess-popen-and-subprocess-call-hang
http://stackoverflow.com/questions/1180606/using-subprocess-popen-for-process-with-large-output
http://stackoverflow.com/questions/16768290/working-of-popen-communicate




# It takes care of standard buffer overflow:

# In not needed: stdout or stderror may be set as: None
# By default, all arguments are initialized to None except   bufsize=0  and  required first argument 'args'
# PIPE => data go to system buffer
# PIPE is needed to redirect the output to a variable
# stdout and stderror could be: None, PIPE, or a file handle

# Note: Popen command (cmd) must be a list
from subprocess import Popen, PIPE, STDOUT
class BaseScript(object):
    @staticmethod
    def runCmd(cmdName):
        p = subprocess.Popen(cmd , shell=True, stdout=PIPE, stderr=PIPE)
        out, err = p.communicate()
        return out.rstrip(), err.rstrip(), p.returncode


# stdout = <file_handle>
f=file('data.out','w')
p = subprocess.Popen(cmd, shell=True, stdout=f, stderr=subprocess.PIPE)
errcode = p.wait()
f.close()
if errcode:
    errmess = p.stderr.read()
    log.error('cmd failed <%s>: %s' % (errcode,errmess))
for line in file('data.out'):
    #do something

Friday, March 11, 2016

pop up script

http://stackoverflow.com/questions/6268675/how-to-show-the-default-beautiful-popup-message-in-ubuntu-using-python

http://stackoverflow.com/questions/1635027/whats-the-simplest-cross-platform-way-to-pop-up-graphical-dialogs-in-python

http://stackoverflow.com/questions/6389580/quick-and-easy-trayicon-with-python

#Command Line: notify-send -t 900 "Title" "Message"

#Script:
import pynotify

# Only Text Notification
pynotify.init('Basic')
pynotify.Notification("Title", "simple text").show()


# Lets try with an image
pynotify.init('Image')
## Use absolute Path of the photo
pynotify.Notification("Title", "My Photo here!!", "/home/nafis/Pictures/me.png").show()

# Try Markup 
pynotify.init("markup") ## all smallerCase "markup"
# but in parameter, first letter capital  
pynotify.Notification("Markup", 
  '''
  <b>bold</b>, <i>italic</i>, <u>underline</u>
  and even <a href="http://google.com">links</a> are supported!
  '''
).show()

Tuesday, March 8, 2016

midi player in python using pygame

https://www.daniweb.com/programming/software-development/code/216979/embed-and-play-midi-music-in-your-code-python

#Note: The script below creates a midi file per data included as string and plays it
==== File in memory based
#!/usr/bin/env python

""" PG_MidiBase64_py23.py
experiments with module pygame from: http://www.pygame.org/
play an embedded midi music file (base64 encoded)
use this short program to create the base64 encoded midi music string
(base64 encoding simply produces a readable string from binary data)
then copy and paste the result into your pygame program
Python2 code ...
import base64
mid_file = "FishPolka.mid"
b64_str = base64.encodestring(open(mid_file, 'rb').read())
print("mid64='''\\\n" + b64_str + "'''")
Python3 code ...
import base64
mid_file = "FishPolka.mid"
b64_str = base64.encodestring(open(mid_file, 'rb').read()).decode("utf8")
print("mid64='''\\\n" + b64_str + "'''")
updated to work with Python2 and Python3 by  vegaseat  16may2013
"""
import pygame
import base64
import io
def play_music(music_file):
    """
    stream music with mixer.music module in blocking manner
    this will stream the sound from disk while playing
    """
    pygame.mixer.music.load(music_file)
    clock = pygame.time.Clock()
    pygame.mixer.music.play()
    # check if playback has finished
    while pygame.mixer.music.get_busy():
        clock.tick(30)
mid64='''\
TVRoZAAAAAYAAQAGAJBNVHJrAAAAJwD/WAQEAhgIAP9ZAgAAAP9RAwfCOwD/BgpGaXNoLVBvbGth
AP8vAE1UcmsAAANoAP8hAQAA/wMOQWNjb3JkaW9uIEhpZ2gAwRUAsQd/ALEKQAD/AQpGaXNoIFBv
bGthAJFOZGhOAAFQYyNQAAFSZBdSADFQZCNQACVOYxdOADFMZCNMACVLYxdLADFJYyNJACVOZCNO
AAFNYyNNAAFOYyNOAAFQZCNQAAFOZCNOAAFMZCNMAAFLZCNLAAFHYyNHAAFLYyNLAAFKYyNKAAFL
YyNLAAFMZCNMAAFLZCNLAAFJZCNJAAFHYyNHAAFCYyNCAAE/YyM/AAFCYyNCAAFHZCNHAAFLZCNL
AAFOYxFOADdQYyNQACVQYyNQACVJYyNJACVJZIEPSQABTGQjTAABS2QjSwABTGMjTAABTmQjTgAB
TGMjTAABS2QjSwABSWMjSQABSGMjSAABSWQjSQABQmMjQgABRmQjRgABSWQjSQABTGQjTAABSWMj
SQABRmQjRgABRGQjRAABQmMjQgABRmQjRgABSWQjSQABTGMjTAABUmMRUgA3UGQjUAAlUGMjUAAl
S2MjSwAlS2SBD0sAAU5jI04AAU1kI00AAU5jI04AAVBjI1AAAU5jI04AAUxkI0wAAUtjI0sAAUdk
I0cAAUtjI0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yUAJCp6ASV7AyoARCUAADlhAiR/AjkAAiQAH7kHdBG5B3ETmSV6ACp4BCoA
QyUAASRuBCQARCV6ACpuBCoAQyUAACRwBCQARCp3ASV7AyoARCUAASRnBCQAQyp2ASV7AyoARCUA
ASRuBCQARCV7ACp6BCoAQyUAASRtBCQAQyp6ASV7AyoARCUAASV6ACRsBCQAQiZ/ASUAAyYAFyZ8
BCYADSZ/BCYAGCZ5Ajl6ACRoAiYAAiQAgQs5AAD/LwA=
'''
# create a memory file object
try:
    # Python27
    midi_str = base64.b64decode(mid64)
    music_file = io.BytesIO(midi_str)
except TypeError:
    # Python3
    midi_bytes = base64.b64decode(mid64.encode())
    music_file = io.BytesIO(midi_bytes)
freq = 44100    # audio CD quality
bitsize = -16   # unsigned 16 bit
channels = 2    # 1 is mono, 2 is stereo
buffer = 1024   # number of samples
pygame.mixer.init(freq, bitsize, channels, buffer)
# optional volume 0 to 1.0
pygame.mixer.music.set_volume(0.8)
try:
    # use the midi file object from memory
    play_music(music_file)
except KeyboardInterrupt:
    # if user hits Ctrl/C then exit
    # (works only in console mode)
    pygame.mixer.music.fadeout(1000)
    pygame.mixer.music.stop()
    raise SystemExit




===== File based
#!/usr/bin/env python

# play an embedded midi music file on your computer's sound card
# experiments with module pygame from: http://www.pygame.org/
# tested with Python25 and PyGame171      vegaseat      04sep2007
"""
# use this short program to create the base64 encoded midi music string
# (base64 encoding simply produces a readable string from binary data)
# then copy and paste the result into your pygame program ...
import base64
mid_file = "FishPolka.mid"
print "mid64='''\\\n" + base64.encodestring(open(mid_file, 'rb').read()) + "'''"
"""
import pygame
import base64
def play_music(music_file):
    """
    stream music with mixer.music module in blocking manner
    this will stream the sound from disk while playing
    """
    clock = pygame.time.Clock()
    try:
        pygame.mixer.music.load(music_file)
        print "Music file %s loaded!" % music_file
    except pygame.error:
        print "File %s not found! (%s)" % (music_file, pygame.get_error())
        return
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy():
        # check if playback has finished
        clock.tick(30)
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5ACRsBCQAACYA
QiZ+BCYAFyZ8BCYADSZ/BCYAGCZ6AiRnAiYAAiQAQiZ/BCYARiRvAjluAiQAAjkAQip3BCoAQyRl
BCQARSpoBCoAQyRmBCQARSpqBCoAQyRoBCQARSpsBCoAQyRoBCQARSprBCoAQyRkBCQARSpuBCoA
QyRjBCQARSpkBCoAQyRmBCQARSppBCoAQyRmBCQARSpxBCoARCRmBCQARCp6BCoARCRoBCQARCpy
BCoARCRlBCQARCp/BCoARSRpBCQAQyp6BCoARCRqBCQAQyp6BCoARSRqBCQARCp6BCoARCRpBCQA
RCp/BCoARSRrBCQAQyV6ACp1BCoAQyUAASRnBCQARCV7ACp7BCoAQyUAASRlBCQARCV7ACp9BCoA
QyUAASRoBCQARCV7ACp1BCoAQyUAASRrBCQARCV6ACp+BCoAQyUAASRpBCQAQyp3ASV7ACRoAyoA
ASQAQyUAASRnBCQARCV7ACp6BCoAICV6IyUAAiRpBCQAHiUAJSV6ACp5BCoAQyUAASRrBCQARCV6
ACp4BCoAQyUAASRwBCQARCV6ACp8BCoAQyUAASRrBCQAQyp6ASV6AyoARCUAASRmBCQARCV6ACp9
BCoAQyUAASRpBCQARCV7ACp3BCoAQyUAASRqBCQARCV7ACp0BCoAQyUAASRqBCQARCV6ACp6BCoA
ICV6IyUAASRlBCQAHyUAJCp6ASV7AyoARCUAADlhAiR/AjkAAiQAH7kHdBG5B3ETmSV6ACp4BCoA
QyUAASRuBCQARCV6ACpuBCoAQyUAACRwBCQARCp3ASV7AyoARCUAASRnBCQAQyp2ASV7AyoARCUA
ASRuBCQARCV7ACp6BCoAQyUAASRtBCQAQyp6ASV7AyoARCUAASV6ACRsBCQAQiZ/ASUAAyYAFyZ8
BCYADSZ/BCYAGCZ5Ajl6ACRoAiYAAiQAgQs5AAD/LwA=
'''
music_file = "FishPolka.mid"
# convert back to a binary midi and save to a file in the working directory
fish = base64.b64decode(mid64)
fout = open(music_file,"wb")
fout.write(fish)
fout.close()
freq = 44100    # audio CD quality
bitsize = -16   # unsigned 16 bit
channels = 2    # 1 is mono, 2 is stereo
buffer = 1024    # number of samples
pygame.mixer.init(freq, bitsize, channels, buffer)
# optional volume 0 to 1.0
pygame.mixer.music.set_volume(0.8)
try:
    # use the midi file you just saved
    play_music(music_file)
except KeyboardInterrupt:
    # if user hits Ctrl/C then exit
    # (works only in console mode)
    pygame.mixer.music.fadeout(1000)
    pygame.mixer.music.stop()
    raise SystemExit




Wednesday, March 2, 2016

install mod_wsgi module for django

https://www.digitalocean.com/community/tutorials/installing-mod_wsgi-on-ubuntu-12-04

http://ericholscher.com/blog/2008/jul/8/setting-django-and-mod_wsgi/eps:


Configuration Steps:

A. create django project in the folder: /root/www/html
run: django-admin startproject mysite

1. Modify /etc/apache2/sites-available/000-default.conf or default
 DocumentRoot /var/www/html/mysite
 WSGIScriptAlias / /var/www/html/mysite/mysite/wsgi.py

2. Modify /etc/apache2/apache2.conf 

append at the end of the file:

WSGIPythonPath /var/www/html/mysite


Tuesday, March 1, 2016

urllib2 GET and POST method

@staticmethod
def delete_job():
jenkins_url = sys.argv[1]
auth = 'Basic ' + base64.encodestring('%s:%s' % ('gopal.singh', '221c13db5d90f39cd987eb20b1deed09'))[:-1]
if jenkins_url[-1] != '/': jenkins_url += '/'
print 'HELLO: ' + jenkins_url
api_url = jenkins_url + 'doDelete'
#api_url = jenkins_url + 'api/json'
get_post = None # '' for POST: None for GET
req = urllib2.Request(api_url, get_post)
req.add_header('Authorization', auth)
return urllib2.urlopen(req).read() # POST method if two args