analitics

Pages

Sunday, September 22, 2013

Jython - funny and simple scripts - first steps .

I play today with jython and can be fun but seams to be to slow in a linux os.

Jython is invoked using the "jython" script and it's an implementation of Python for the JVM.

Install the package jython in your linux distro and you can start to deal with java and python.

When you use jython then script will start with :

#!/usr/bin/env jython

I make also some very simple scripts...

First script make one button and give a action to exit.


#!/usr/bin/env jython
from javax import *
import java
from java import *
import sys

frame = awt.Frame(size=(500,100))
frame.background = 255,255,0
def exit(event):
  java.lang.System.exit(0)

my_button = awt.Button("Exit!", actionPerformed=exit)
frame.add(my_button,"Center")
frame.pack()
frame.setVisible(1)

The output is:


The script is easy to make ... it's like gtk with add, pack and action ...

Let's see the next script : one list.

from javax import *
from java import awt
import sys
python_list=[]
python_list.append('text 1')
python_list.append('text 2')
python_list.append('text 3')
python_list.append('text 4')
python_list.append('text 5')

frame=awt.Frame("test list")
panel=swing.JList(python_list)
frame.add(panel,"Center")
frame.pack()
frame.setVisible(1)

... and this is the gui with the list:


I make a simple list and add to the gui using pack() function.

The jython is not easy is much to learn and if you want then go to this website.

Check system , distro and commands using python scripts .

This is a simple example with two functions.

First will check the linux command : ls linux command.

The next function will give us some infos about system.

import shlex 
import subprocess
from subprocess import Popen, PIPE

import platform

def check_command(command):
    cmd='which ' + command 
    output = Popen(shlex.split(cmd), stdout=PIPE).communicate()[0]
    command_path =output.split('\n')[0]
    print command_path
    return command_path

def check_platform():
    arch, exe = platform.architecture()
    my_system = platform.system()
    if my_system == 'Linux':
        distro_name, distro_version, distro_id = platform.linux_distribution()
    elif my_system == 'Darwin':
        distro_name, distro_version, distro_id = platform.mac_ver()
    elif my_system == 'Windows':
 distro_name, distro_version, distro_id = platform.win32_ver()
    elif my_system == 'Java':
 distro_name, distro_version, distro_id = platform.java_ver()
    processor = platform.processor() or 'i386'
    print processor, my_system, arch, distro_name, distro_version, distro_id
    return processor, my_system, arch, distro_name, distro_version, distro_id

check_command('ls')

check_platform()

This python script can be use with any scripts when we need to test commands and system , distro version.

Thursday, September 12, 2013

Working with SunPy python module - part 001 .

The SunPy python module it's an open-source software library for solar physics using the Python programming language.

The SunPy module is included into nasa projects.

Now, if you want to use this python module then you need to install lapack and blas libraries for development.

I use # pip under super user account to install sunpy and the python modules required by SunPy.

# pip install --upgrade distribute
# pip install --upgrade pyfits
# pip install --upgrade suds
# pip install --upgrade pandas
# pip install --upgrade beautifulsoup4

... also you need to have this python modules: Scipy and Matplotlib.

After that you can install sunpy using:

# pip install sunpy
# pip install --upgrade sunpy

The basic example is one output created by Map() function.

This function can deal with many data sources, like:

SDO/AIA, SDO/HMI

STEREO/EUVI, STEREO/COR

Hinode/XRT

SOHO/EIT, SOHO/LASCO, SOHO/MDI

PROBA2/SWAP

Yohkoh/SXT

Let's try a simple example and will show the result...

>>> import sunpy 
>>> ati_map=sunpy.Map(sunpy.AIA_171_IMAGE).peek()

... and output is:


Let's make more sun maps...

>>> eit_map=sunpy.Map(sunpy.EIT_195_IMAGE).peek()

The the output is:


>>> rhessi_map=sunpy.Map(sunpy.RHESSI_IMAGE).peek()

You can see radio spectrometer image using:

>>> callisto_radio_maps=sunpy.Map(sunpy.CALLISTO_IMAGE).peek()

Also you can combine the maps , like in the next example:

>>> eti_rhessi_maps=sunpy.Map(sunpy.EIT_195_IMAGE, sunpy.RHESSI_IMAGE, composite=True).peek()

You can get more infos about Map using :

>>> help(sunpy.Map)

If you want more data to show then you can request data from here.

Also you can give parameters to the Map, like:

date : datetime
 |          Image observation time
...

This allow you to take more data and info...

Using matplotlib and scipy modules can help to parse and show all infos.

How to fix error: fatal error: Python.h: No such file or directory

This is a common error when your system don't have the python-dev.

I got this error when I try to use : pip .

Just install the package python-dev and then all will working well.

Monday, September 9, 2013

News - Python 3.4.0 Alpha 2 was released .

From python official website I found this :

Python 3.4.0 alpha 2 was released on September 9th, 2013. This is a preview release of the next major release of Python, Python 3.4, and is not suitable for production environments.

Major new features of the 3.4 series, compared to 3.3

Python 3.4 includes a range of improvements of the 3.x series, including hundreds of small improvements and bug fixes. Major new features and changes in the 3.4 release series so far include:

PEP 435, a standardized "enum" module

PEP 442, improved semantics for object finalization

PEP 443, adding single-dispatch generic functions to the standard library

PEP 445, a new C API for implementing custom memory allocators

PEP 446, changing file descriptors to not be inherited by default in subprocesses...

Saturday, August 17, 2013

Working with PEP 8 conventions ...

I am wrote my own python scripts to long time ago and now I saw many of this scripts are a mess  in terms of PEP criteria.
What is the pep criteria? The PEP describing style guidelines for the C code in the C implementation of Python.
If you using Blender 3D/Python development  then you need to follow the PEP 8.
The PEP 8 and can be found here and the authors are: Guido van Rossum , Barry Warsaw and Nick Coghlan.
Today I will show you a brief listing of pep8 criteria:
-indentation of 4 spaces not use tabs
-camel caps for class names: MyClass , AnotherClass
-all lower case underscore separated module names: my_module, another_module
-use explicit imports, not importing '*'
-imports should usually be on separate lines, not import os,sys
-adding whitespace around the operators , not 1+2 or 7+ 3
-don't use spaces around the = sign , not a = b +1
-use single quotes for enums, and double quotes for strings
-each line of a block comment starts with a # and a single space
-don't make comments that contradict the code
-if you want to writing good documentation strings then follow the PEP 257 conventions.
-run checks for pep8 compliance
# <pep8 compliant=""></pep8>
-and enable line length checks use this instead
# <pep8-80 compliant=""></pep8-80>
-don't use multiple statements on the same line, like:
if foo == 'test': do_test_thing()
one_test(); two_test()
... this is the correct way:
if foo == 'test':
    do_test_thing()
one_test()
two_test()
Also you can read about Blender 3D/Python and PEP 8 best practice here.

Saturday, August 10, 2013

Fix python error: SyntaxError: Non-ASCII character.

This can be fix easy ... just add the below line at top of the python file:
# coding: utf-8
You will see now something like this error:
SyntaxError: invalid syntax
... but also will be point to the bad encoding character with : ^
For example I had this:
usertest@home:~$ python sunet.py 
  File "sunet.py", line 22
    def  __init__ ( self , a , b , c ) :
                                 ^
SyntaxError: invalid syntax

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.

Tuesday, July 30, 2013

The new pygobject come with version 3.9.5 .

GObject is a object system used by GTK+, GStreamer and other libraries.

The new PyGObject 3.9.5 provides a convenient wrapper for use in Python programs when
accessing GObject libraries.

The news come from Simon Feltman - pygtk digest: I am pleased to announce version 3.9.5 of the Python bindings for
GObject. This is the third release of the 3.9.x series which will
eventually result in the stable 3.10 release for GNOME 3.10.

The new release is available from ftp.gnome.org.

Wednesday, July 24, 2013

Using python module webkit and gtk to make one simple webbrowser.

Today I will show you a simple example with webkit python module.

I will make one simple browser using this two python modules.

Read the full tutorial here.

The result can be see in the next image:

Sunday, July 14, 2013

Selenium python module and links.

Just see my old tutorial to run the selenium module.
NOTE: If your script not run when you try to login then use python shell :P
Now add the next source code to see the links and some infos.
links = browser.find_elements_by_partial_link_text('')
for link in links:
    print link.get_attribute("href")

Saturday, July 13, 2013

Selenium python module and cookies.

Today I will show how to deal with cookies and Firefox.

Selenium Python Client Driver is a Python language binding for Selenium Remote Control.

You can read more about this module here.

You can find some examples , but most of webpages working with cookies.So let's make one simple tutorial.

The next source code is very simple and most of the python users knows what means.


$ python 
Python 2.7.3 (default, Jan  2 2013, 16:53:07) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from selenium import webdriver
>>> from selenium.common.exceptions import NoSuchElementException
>>> from selenium.webdriver.common.keys import Keys
>>> browser = webdriver.Firefox()
>>> browser.get("http://facebook.com/")
>>> browser.get("http://facebook.com/home.php")

The next source codes will get your cookies from the webpage.

>>> for cookie in browser.get_cookies():
...     print(cookie['name'] + ' --> your cookie data ' + cookie['value'])
... 
datr --> your cookie data 
locale --> your cookie data 
xs --> your cookie data 
s --> your cookie data 
lu --> your cookie data 
fr --> your cookie data 
csm --> your cookie data 
c_user --> your cookie data 
act --> your cookie data 
x-src --> your cookie data 
sub --> your cookie data 
p --> your cookie data 
presence --> your cookie data 
>>> 

You can deal with all functions of selenium python module , see :

>>> dir(browser)
['NATIVE_EVENTS_ALLOWED', '__class__', '__delattr__', '__dict__', '__doc__', 
'__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__'
, '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__'
, '__subclasshook__', '__weakref__', '_is_remote', '_unwrap_value', '_wrap_value'
, 'add_cookie', 'application_cache', 'back', 'binary', 'capabilities', 'close', 
'command_executor', 'create_web_element', 'current_url', 'current_window_handle'
, 'delete_all_cookies', 'delete_cookie', 'desired_capabilities', 'error_handler'
, 'execute', 'execute_async_script', 'execute_script', 'find_element', 
'find_element_by_class_name', 'find_element_by_css_selector', 'find_element_by_id'
, 'find_element_by_link_text', 'find_element_by_name', 'find_element_by_partial_link_text'
, 'find_element_by_tag_name', 'find_element_by_xpath', 'find_elements', 
'find_elements_by_class_name', 'find_elements_by_css_selector', 'find_elements_by_id',
 'find_elements_by_link_text', 'find_elements_by_name', 'find_elements_by_partial_link_text'
 , 'find_elements_by_tag_name', 'find_elements_by_xpath', 'firefox_profile', 'forward',
  'get', 'get_cookie', 'get_cookies', 'get_screenshot_as_base64', 'get_screenshot_as_file'
  , 'get_window_position', 'get_window_size', 'implicitly_wait', 'is_online', 
  'maximize_window', 'name', 'orientation', 'page_source', 'profile', 'quit', 'refresh'
  , 'save_screenshot', 'session_id', 'set_page_load_timeout', 'set_script_timeout', 
  'set_window_position', 'set_window_size', 'start_client', 'start_session', 'stop_client'
  , 'switch_to_active_element', 'switch_to_alert', 'switch_to_default_content', 
  'switch_to_frame', 'switch_to_window', 'title', 'window_handles']

This module can be a way for you to testing your webpages , save cookie , restore and more...

Also , if you know networking development also you can use scapy module to test more.

I hope will like this simple tutorial about python.

Monday, July 8, 2013

Using findContours from OpenCV python module.

Today I will show something nice about OpenCV Analysis and Shape Descriptors.

This function finds contours in a binary image.

All detected contours is stored as a vector of points for each contour.


#!/usr/bin/python2.7
import cv2
im = cv2.imread('your_image.jpg')
img_gray = cv2.cvtColor(im,cv2.COLOR_RGB2GRAY)
ret,thresh = cv2.threshold(img_gray,127,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(im,contours,-1,(250,250,250),2)
cv2.imshow('your_image.jpg',im)
cv2.waitKey()
cv2.destroyAllWindows()

If you got this error:

findContours error 'support only 8uC1 images'

then the main reason it's findContours requires a monochrome image.

Let's see the result of the python script.


The contour it's draw with 250,250,250 color.