Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Wednesday, 14 October 2009

HOWTO install egg file for python

Using easy_install, which is installed by setuptools (http://pypi.python.org/pypi/setuptools).

~$ easy_install XXXXX.egg
This is for binary egg file. While script egg file should be treated as normal shell script. To install:
~$ sh XXXXXX.egg

#######################
Another popular way to install python 'modules', is:
~$ python setup.py install
This is from python source. Normally third parties will provide such kind of source.

Monday, 26 January 2009

Jython and Matlab do jobs for java

Java codes:
======================
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyExample
implements ActionListener {

public void actionPerformed(ActionEvent e) {
System.out.println("Ouch!");
}

public static void main(String[] args) {
JFrame frame = new JFrame("My Frame");
frame.setSize(300,300);
JButton button = new JButton("Push Me!");
ActionListener listener = new MyExample();
button.addActionListener(listener);
frame.getContentPane().add(button);
frame.setVisible(true);
}
}


Jython:
======================
import javax.swing as swing

def printMessage(event):
print "Ouch!"

frame=swing.JFrame("my frame")
frame.setSize(300,300)
button=swing.JButton("Push Me!")
button.actionPerformed=printMessage
frame.getContentPane().add(button)
frame.setVisible(True) #frame.visible=1


Matlab:
=======================
import javax.*;

frame = swing.JFrame('my frame');
frame.setSize(300,300);
button = swing.JButton('Push Me!');

set(button,'ActionPerformedCallback',@printMessage);

frame.getContentPane.add(button);
frame.setVisible(true);

%code for sub function:
function printMessage(handle,event)
disp('ouch');
end

Thursday, 27 November 2008

HOWTO: jython(java) calling c program in console

import java.lang

proc=java.lang.Runtime.getRuntime().exec("c:\\app.exe") // this app.exe is compiled from c
br=java.io.BufferedReader(java.io.InputStreamReader(proc.getInputStream()))
print br.readLine()
java.lang.System.out.println("last line")

=========================
Why not using os.popen() from python, is because there is a bug about calling popen. :)

Wednesday, 26 November 2008

efficiency of python calling c exetuable

python 可以用popen调用一个c语言的可执行程序。但是效率如何呢?

1)一个c程序: 调用一个循环求和从1到1000的function 10000次。
之所以要调用循环求和从1到1000,是因为这个function要声称另外的一个可执行文件供python调用,所以外部框架c和python都差不多,就是要往复调用这个function,以得出python与c的沟通效率。
#######################
/*
* File: newmain.c
* Author: cross
*
* Created on 26 November 2008, 16:08
*/

#include <stdio.h>
#include <stdlib.h>

struct timeb {
time_t time;
unsigned short millitm;
short timezone;
short dstflag;
};
//ftime returns a struct with above structure.

int internal_loop(){
int ii=0,ss=0;
while (ii<1000)
{
ss+=ii;
ii++;
}
printf("%i\n",ss);
return ss;
}

int main(int argc, char** argv) {

struct timeb t1,t2;
double i=0,s=0;

ftime(&t1);

int repeat = 10000;
while(i<repeat){
s+=internal_loop();
i++;
}

ftime(&t2);
printf("%.1f\n",s);

printf("time = %ld.%d\n",t1.time,t1.millitm);
printf("time = %ld.%d\n",t2.time,t2.millitm);


return (EXIT_SUCCESS);
}


##################

2)以上的internal_loop function被单独生成一个c的可执行文件b.o,供python调用。以下是python代码。
##################

import datetime
import os

t1= datetime.datetime.now()

j=0
k=1000
for i in range(1,k):
printed=os.popen('/home/cross/NetBeansProjects/Application_2/b.o')
printed.readlines()
printed.close()

print # to print a new line

t2= datetime.datetime.now()

tstr=[(t2-t1).seconds,(t2-t1).microseconds] # the attributes of timedelta class: senconds and microseconds, from http://docs.python.org/lib/datetime-timedelta.html#l2h-602
print 'Repeated sum of 1-1000 ',k,' times : '
print tstr

###############

3) 只用python单独完成和1)一样的过程,python代码如下:
########################
import datetime

t1= datetime.datetime.now()

k=10000
for i in range(1,k):
    j=0
    for ii in range(1,1000):
        j=j+ii
    print j

print # to print a new line

t2= datetime.datetime.now()

tstr=[(t2-t1).seconds,(t2-t1).microseconds] # the attributes of timedelta class: senconds and microseconds, from http://docs.python.org/lib/datetime-timedelta.html#l2h-602
print 'Repeated sum of 1-1000 ',k,' times : '
print tstr

#####################


总结
如果成功运行以上两个程序,同样是运行10000次,1)耗时274毫秒;2)20秒。
可见python与其他程序通过popen这种字符沟通的效率是比较低的。以上,1)是同一个程序调用一个子函数,速度当然是最理想的。而2)是通过console的字符交换得以沟通,这种效率当然低,甚至这还远不如主程序和子程序的沟通效率。

通过1)和3)的比较,可以很容易看出来python的语法简单,但是python比c慢也是事实,3)用时3.8秒。

HOWTO: Calling c (or other programs) from python

Calling c (or other programs) from python

1. swig (to generate a python extention from c)
2. dl, python object (to call c shared library)
3. os.popen() (to call other exetuable programs)

In this example, I will use the 3rd method.

1) c program.
This is an example from netbeans, it can print all the arguments, argv[0] is the program name.
# args.c ###################################
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char**argv) {
int i;
// Prints arguments
printf("Arguments:\n");
for (i = 0; i < argc; i++) {
printf("%i: %s\n", i, argv[i]);
}

return 0;
}
#############################
compile it:
####
gcc args.c -o a.out
####

2) python script

# in python script ################
import os
printed = os.popen('./a.o hello world')
>>> printed.readline()
'Arguments:\n'
>>> printed.readline()
'0: ./a.o\n'
>>> printed.readline()
'1: hello\n'
>>> printed.readline()
'2: world\n'
>>> printed.readline()
''
##################################
Here printed is an python array object, all the methods for array are available.

Tuesday, 12 February 2008

python run system command: os.exec.....

Python can call other program easily. Here are some ways:

import os

os.chdir('the path your program is in')
os.execv('WinProgram.exe',['argv[0]','other parameter']) # here the first one will not passed to the program!!!! And execv requires the arguments are in one list or turtle.
##os.execl('WinProgram.exe','argv[0]','other parameter')
##os.system('WinProgram.exe'+' '+'other parameter')

Here os.system just run the command, while execl and execv will stop current process and turn to another one, the rest codes will not run.

Saturday, 9 February 2008

python change working directory

Sometimes this concept of working directory is essential, especially when calling another system or executable programs.

import os

os.chdir('c:\\thepath\\')
os.system('the command') # otherwise, if the command need to read some file within same folder, the command can not find it, because the needed file is not in the current working directory.


Powered by ScribeFire.

Friday, 8 February 2008

Tkinter layout/alignment control

The following example uses packer management for the Tkinter layout.

Reference: http://docs.python.org/lib/node695.html


from Tkinter import *

root=Tk()

b3=Button(root, text='click me!!')
b3.pack(padx=10,pady=5)

b1=Button(root, text='click me',padx=10,pady=5)
b1.pack(side = "left")

b2=Button(root, text='click me',padx=10,pady=5)
b2.pack(side = 'right',expand = 1)

b4=Button(root, text='click me',padx=10,pady=5)
b4.pack()


root.mainloop()




Powered by ScribeFire.

Saturday, 26 January 2008

python workspace, a little bit global

a=100

def first():
b=a+1
c=a+2
return b,c

def second():
d=bb+11
e=cc+12
return d,e

class thirdC:
def fourth(self):
f=dd+101
g=ee+102
return f,g
def fifth():
h=ff+1001
i=gg+1002
(j,k)=second()
return h,i,j,k

if __name__=='__main__':
(bb,cc)=first()
(dd,ee)=second()
tc=thirdC()
(ff,gg)=tc.fourth()
(hh,ii,jj,kk)=fifth()

Wednesday, 23 January 2008

HOWTO: listbox in Python Tkinter

alist=[' x ',' xin ','zhengxin',' shan ',' shanshan ','shanshan cheng ']
##aset=set(alist)
##b=set()
##
##for aitem in aset:
## if aitem.find('xi')!=-1:
## print aitem,':item will be removed'
## b.add(aitem)
##
##c=aset-b
##print aset
##print c

from Tkinter import *
class MyDialog:
def __init__(self,master):
MyDialog.removed=list()
Label(text="one").pack()
self.s = Frame()
self.s.pack()

self.listbox = Listbox(self.s,selectmode=EXTENDED)
self.listbox.pack()

for item in alist:
self.listbox.insert(END, item)

Label(text="two").pack()

self.b = Button(master, text="Delete",command = self.toremove)
## self.b = Button(master, text="Delete",command = lambda lb=lb: lb.delete(ANCHOR))
self.b.pack()

def toremove(self):
# Select what to remove and save them to the Class Variable MyDialog.removed
self.items = self.listbox.curselection()
for i in self.items:
MyDialog.removed.append(self.listbox.get(i))
print self.listbox.get(i)

# To sort the sequence,then reverse, then delete.
self.iitems=list()
for i in range(len(self.items)):
self.iitems.append(int(self.items[i]))
self.iitems.sort()
self.iitems.reverse()
for j in self.iitems:
self.listbox.delete(j)
## def toremove(self):
## self.listbox.delete(ANCHOR)


if __name__=='__main__':
root = Tk()
d = MyDialog(root)
root.mainloop()

HOWTO: lambda in Python

By popular demand, a few features commonly found in functional programming languages like Lisp have been added to Python. With the lambda keyword, small anonymous functions can be created. Here's a function that returns the sum of its two arguments: "lambda a, b: a+b". Lambda forms can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda forms can reference variables from the containing scope:

>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43


lambda很灵活,可以用在任何需要函数的地方:

>>>def f(x):
… return x*2

>>> f(2)
4

定义一个函数f(x),f(x)=x*2. 用lambda来表达就是:

>>> f=lambda x: x*2
>>> f(2)
4

这个函数没有函数名,lambda的结果被赋值给变量f调用。

############################################
对于Tkinter,
可以直接用lambda直接设置一些简单callback:
b = Button(master, text="Delete",command = lambda listbox=listbox: listbox.delete(ANCHOR))
在这种情况下,需要设定返回值(listbox=),然后才是lambda的参数(listbox).

这种简写方式等效于:(如下code是在一个class内的代码)

self.b = Button(master, text="Delete",command = self.toremove)
##self.b = Button(master, text="Delete",command = lambda llb=lb: lb.delete(ANCHOR))
def toremove(self):
self.listbox.delete(ANCHOR)

Powered by ScribeFire.

Tuesday, 22 January 2008

Create class for GUI , Python

from Tkinter import *

class MyDialog:
def __init__(self, top):
Label(top, text="Value").pack()

self.e = Entry(top)
self.e.pack(padx=5)

b = Button(top, text="OK", command=self.ok)
b.pack(pady=5)

def ok(self):
print "value is", self.e.get()

root = Tk()
d = MyDialog(root)
root.mainloop()

Python Tkinter-Checkbutton

Cited from: http://effbot.org/tkinterbook/checkbutton.htm

To use a Checkbutton, you must create a Tkinter variable. To inspect the button state, query the variable.

from Tkinter import *

master = Tk()

var = IntVar()

c = Checkbutton(master, text="Expand", variable=var)
c.pack()

mainloop()

By default, the variable is set to 1 if the button is selected, and 0 otherwise. You can change these values using the onvalue and offvalue options. The variable doesn’t have to be an integer variable:

    var = StringVar()
c = Checkbutton(
master, text="Color image", variable=var,
onvalue="RGB", offvalue="L"
)

If you need to keep track of both the variable and the widget, you can simplify your code somewhat by attaching the variable to the widget reference object.

    v = IntVar()
c = Checkbutton(master, text="Don't show this again", variable=v)
c.var = v

If your Tkinter code is already placed in a class (as it should be), it is probably cleaner to store the variable in an attribute, and use a bound method as callback:

    def __init__(self, master):
self.var = IntVar()
c = Checkbutton(
master, text="Enable Tab",
variable=self.var,
command=self.cb)
c.pack()

def cb(self, event):
print "variable is", self.var.get()

Example:

from Tkinter import *

def cb1():
print 'use c.var.get() to check the checkbutton value'

master=Tk()
v = IntVar()
c = Checkbutton(master, text="Color Image", variable=v, command=cb1)
c.var=v
c.pack()
master.mainloop()

Saturday, 19 January 2008

simple python gui

from Tkinter import *
root = Tk()

w = Label(root, text="Hello, world!")
w.pack()

root.mainloop() # if runs in IDLE, comment this line, otherwise errors occur.

Friday, 18 January 2008

python arguments

What if you want to supply arguments to the Python script? The sys module contains a variable called argv. It is an array that contains the name of the Python file and any command line arguments that followed.

For example, let's define a file called show_args.py;

import sys
print sys.argv

Now when we evaluate show_args.py with Python, we'll simply see the arguments we entered on the command line, along with the filename of the script:

% python show_args.py 1 2 3 4 5
['show_args.py', '1', '2', '3', '4', '5']
%

Notice that sys.argv is an array, so you can refer to individual commands using the [] array element syntax. You can also use any array function on sys.argv or on a part of it (using the [:] syntax).

Here's file show_args_2.py that extracts elements from the sys.argv array:

import sys, string

print 'The arguments of %s are "%s"' % \
(sys.argv[0], string.join(sys.argv[1:]))

(The "\" character lets me continue the print command to the next line by nullifying the "newline" character that would otherwise create a new line.) We'll run this script with the same command-line arguments we used for show_args.py:

% python show_args_2.py 1 2 3 4 5
The arguments of show_args_2.py are "1 2 3 4 5"
%

The sys.argv array consists of strings, so you will need to convert number arguments to numbers using the conversion functions int or float. For example, let's make our pi multiplying script take an argument. We'll call it pi_mult.py:

import math, sys

def times_pi(value):
return math.pi * value

value = float(sys.argv[1])

print '%g times pi is %g' % (value, times_pi(value))

Now when we run it with a command-line argument, that argument is changed into a float before it is multiplied by math.pi:

% python pi_mult.py 2
2 times pi is 6.28319
%

But what if we forget to enter an argument on the command line? We'll get an error message (since there is no second element to the sys.argv array) and Python will stop evaluating the script file:

% python pi_mult.py
Traceback (most recent call last):
File ``pi_mult.py'', line 6, in ?
value = float(sys.argv[1])
IndexError: list index out of range
%

By convention, Unix commands will provide a ``usage'' message if the arguments are wrong. The usage message lists descriptions of the arguments (enclosed in "<" and ">" characters) so you know what kind of arguments the command requires. We can add a check for the right number of arguments to our command, and print out the usage message if the argument count is incorrect.

We'll make a new version, called pi_mult_2.py, in which we add the argument check and the usage message:

import math, sys

if len(sys.argv) != 2:
print 'Usage: pi_mult_2.py '
sys.exit(1)

def times_pi(value):
return math.pi * value

value = float(sys.argv[1])

print '%g times pi is %g' % (value, times_pi(value))

Now when we try to run pi_mult_2.py without arguments, the number of command line arguments is wrong; it should be 2: one for the script filename and one for the number to be multipled by pi. The usage message will be printed instead of causing a Python error:

% python pi_mult_2.py
Usage: pi_mult_2.py
%

Thursday, 17 January 2008

python read files

Doing it the usual way

The standard idiom consists of a an ‘endless’ while loop, in which we repeatedly call the file’s readline method. Here’s an example:

# File: readline-example-1.py

file = open("sample.txt")

while 1:
line = file.readline()
if not line:
break
pass # do something

This snippet reads the file line by line. If readline reaches the end of the file, it returns an empty string. Otherwise, it returns the line of text, including the trailing newline character.

On my test machine, using a 10 megabyte sample text file, this script reads about 32,000 lines per second.
Using the fileinput module

If you think the while loop is ugly, you can hide the readline call in a wrapper class. The standard fileinput module contains an input class which does exactly that.

# File: readline-example-2.py

import fileinput

for line in fileinput.input("sample.txt"):
pass

However, adding more layers of Python code doesn’t exactly help. For the same test setup, performance drops to 13,000 lines per second. That’s nearly two and half times slower!
Speeding up line reading

To speed things up, we obviously need to make sure we spend as little time on in Python code (running under the interpreter) as possible.

One way to do this is to tell the file object to read larger chunks of data. For example, if you have enough memory, you can slurp the entire file into memory, using the readlines method. Or you could even use the read method to read the entire file into a single memory block, and then use string.split to chop it up into individual lines.

However, if you’re processing really large files, it would be nice if you could limit the chunk size to something reasonable. For example, if you read a few thousand lines at a time, you probably won’t use up more than 100 kilobytes or so.

The following script uses a nested loop. The outer loop uses readlines to read about 100,000 bytes of text, and the inner loop processes those lines using a simple for-in loop:

# File: readline-example-3.py

file = open("sample.txt")

while 1:
lines = file.readlines(100000)
if not lines:
break
for line in lines:
pass # do something

Can this really be faster? You bet. With the same test data, we can now process 96,900 lines of text per second!

Or to put it another way, this solution is three times as fast as the standard solution, and over seven times faster than the fileinput version.

In Python 2.2 and later, you can loop over the file object itself. This works pretty much like readlines(N) under the covers, but looks much better:

# File: readline-example-5.py

file = open("sample.txt")

for line in file:
pass # do something

In Python 2.1, you have to use the xreadlines iterator factory instead:

# File: readline-example-4.py

file = open("sample.txt")

for line in file.xreadlines():
pass # do something

Copyright © 2000 Fredrik Lundh

Powered by ScribeFire.

Monday, 14 January 2008

del in python

del in python workspace

del(XX) or del XX

Python reads configuration file

The ConfigParser module in the standard library already does this:

import ConfigParser

cfg = ConfigParser.ConfigParser()
cfg.readfp(open('myconfig.ini'))
print cfg.get('system', 'database')


----

The configuration file consists of sections, led by a "[section]" header and followed by "name: value" entries, with continuations in the style of RFC 822; "name=value" is also accepted. Note that leading whitespace is removed from values. The optional values can contain format strings which refer to other values in the same section, or values in a special DEFAULT section. Additional defaults can be provided on initialization and retrieval. Lines beginning with "#" or ";" are ignored and may be used to provide comments.

For example:

[My Section]
foodir: %(dir)s/whatever
dir=frob

would resolve the "%(dir)s" to the value of "dir" ("frob" in this case). All reference expansions are done on demand.

Default values can be specified by passing them into the ConfigParser constructor as a dictionary. Additional defaults may be passed into the get() method which will override all others.

---------------------------

Python 本身没有数组这个说法, 有的就是list和tuple, list就具有其他语言中的数组特性.
至于list和tuple的区别,在于list可以在运行时修改内容和大小,tuple在首次创建和赋值后, 不可以再次修改内部的内容
不过python 有提供一个array模块,用于提供基本数字,字符类型的数组.用于容纳字符号,整型,浮点等基本类型.

import array
#建立一个整数数组,初始内容是1,2,3,4,5
array.array('l', [1, 2, 3, 4, 5])

这种模块主要用于二进制上的缓冲区,流的操作.

Python中Array的常用操作数组基本操作

1. 定义数组

>>> seq = [ “a” , “b” , 1 ]

[ “a” , “b” , 1 ]

2. 创建数组

>>> a = “what are you doing?”.split()

[’what’, ‘are’, ‘you’, ‘doing?’]

>>> a = [ x*2 for x in range(1,5) ]

[2, 4, 6, 8]

b = [ x for x in a if x >3 ]

[ 4, 6, 8]

-----------------------------------------------------------

1. 数组操作

x代表数组中的元素,i代表位置

a) append(x) 把元素x添加到数组的尾部

b) insert(i,x) 把元素x 插入到位置i

c) remove(x) 删除第一个元素x

d) pop(i) 删除第i个元素,并返回这个元素。若调用pop()则删除最后一个元素

e) index(x) 返回数组中第一个值为x的位置。如果没有匹配的元素会抛出一个错误

f) count(x) 返回x在数组中出现的次数

g) sort() 对数组中的元素进行排序

h) reverse() 对数组中的元素用倒序排序

>>> a = [ x*2 for x in range(1,5) ]

[2, 4, 6, 8]

>>> del a[0]

[4, 6, 8]

>>> a = [ 1 , 2 ] + a

[1, 2, 4, 6, 8]

>>> a += [None]*2

[1, 2, 4, 6, 8, None, None]

>>> a.remove(1)

[2, 4, 6, 8, None, None]

>>> a.pop()

[2, 4, 6, 8, None,]

>>> a.append(100)

[2, 4, 6, 8, None, 100]

>>> a.insert(0,8)

[8, 2, 4, 6, 8, None, 100]

>>> a.count(8)

2

>>> a.index(2)

1

2. 遍历数组

>>> a = [ x*2 for x in range(1,5) ]

[2, 4, 6, 8]

>>> for x in a:

… print x

>>> for i, x in enumerate(a):

… print x

>>> b = [ x+100 for x in a]

>>> for i,j in zip(a,b):

… print i,j

array in python

Two types of array:

1. the array comes with Python.
import array
a=array.array('f',[1,2,3])
aa=a*2 # got array('f',[1.0,2.0,3.0,1.0,2.0,3.0])
print a #not suitable for numerical calculation,http://docs.python.org/lib/module-array.html

2.Numpy (third party modules, need to download from http://numpy.scipy.org
from numpy import *
b=
array([1,2,3])
bb=b*2 # got array([2, 4, 6])

P.S.: the two types can exist simultaneously, but when they are calculated together, the 'array.array' will be converted to 'numpy.array' automatically.
>>> import numpy
>>> a=numpy.array([1,2,3])
>>> import array
>>> b=array.array('f',[0.1,0.1,0.1])
>>> print a
[1 2 3]
>>> print b
array('f', [0.10000000149011612, 0.10000000149011612, 0.10000000149011612])
>>> c=a+b
>>> print c
[ 1.1 2.1 3.1]

>>> a
array([1, 2, 3])
>>> b
array('f', [0.10000000149011612, 0.10000000149011612, 0.10000000149011612])
>>> c
array([ 1.1, 2.1, 3.1])
>>>

My photo
London, United Kingdom
twitter.com/zhengxin

Facebook & Twitter