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

Wednesday, March 18, 2015

python with win32 api

ref: http://sourceforge.net/projects/pywin32/

import win32com.client
import win32api
import win32con
import time

def IsPressed(key):
    # ref: https://msdn.microsoft.com/en-us/library/windows/desktop/ms646301%28v=vs.85%29.aspx
    return win32api.GetKeyState(key) & 0x8000 == 0x8000

exit = False;
# for tracking key state
prevSpace = 0;
prevUp = 0;
currentSpace = 0;
currentUp = 0;

# loop to track key state
while (exit == False):
    currentSpace = IsPressed(win32con.VK_SPACE);
    currentUp = IsPressed(win32con.VK_UP);
    if IsPressed(win32con.VK_ESCAPE):
       exit = True;
       print "Escape"
    prevSpace = currentSpace;
    prevUp = currentUp;
    time.sleep(0.0001)


# if need to send key to another app
shell = win32com.client.Dispatch("WScript.Shell")
shell.AppActivate("app to activate or send key to ...")
shell.SendKeys("whatever key to send", 0)

python with de facto GUI library. standard library Tk


from Tkinter import *

def bClick():
    t.set(t2.get())

root = Tk()
t = StringVar()
t2 = StringVar()

# create UI elements
label = Label(root, textvariable=t)
entry = Entry(root, textvariable=t2)
b = Button(root, text="Click Me!", command = bClick)

# layout UI elements
label.pack()
entry.pack()
b.pack()

t.set("Hello Label");

root.mainloop()

Thursday, July 17, 2014

python: open a file to read, then replace string, write back to file

f = open('file.txt', 'r');
s = f.read();
print s
s = s.replace('\n', '\\n');
s = s.replace('\r', '');
# print s
f.close();
f = open('file_replaced.txt', 'w');
f.write(s);
f.close();

print "file written"

Wednesday, January 15, 2014

IronPython with C#

using python in c#
http://ironpython.codeplex.com/releases/view/28125
http://blogs.msdn.com/b/charlie/archive/2009/10/25/hosting-ironpython-in-a-c-4-0-program.aspx

started console project.
works!

Test.cs
namespace TestPython
{
    public class Test
    {
        int a = 10;
        public int A { get { return a; } }
        public void Method1()
        {
            Console.WriteLine(a);
        }
        public int Method2(int b)
        {
            return a + b;
        }
    }
}

Test.py
import sys
import clr

class MyPyClass:
  myvar = 123
  def _init_(self):
    print "constructor"
  def m1(self):
    print self.myvar

def Simple():
  print "Hello from Python"
  a = 3
  a = a *4
  print a

  # instantiate C# class
  clr.AddReference('TestPython') # can be replaced with "ipy.LoadAssembly(System.Reflection.Assembly.GetExecutingAssembly());" in C#, if necessary
  from TestPython import *
  b = Test();
  b.Method1();

Program.cs
namespace TestPython
{
    class Program
    {
        static void Main(string[] args)
        {
            var ipy = Python.CreateRuntime();
            dynamic test = ipy.UseFile("Test.py");
            test.Simple();

            // use python class in c#
            var instance = test.MyPyClass();
            instance.m1();
         
            Console.WriteLine("Bye");
            Console.ReadLine();
        }
    }
}

Friday, December 28, 2012

Mac OS X: pyglet


installed pyglet
tried a simple app and run, get the following error:

OSError: dlopen(/System/Library/Frameworks/QuickTime.framework/QuickTime, 6): no suitable image found.  Did find:
 /System/Library/Frameworks/QuickTime.framework/QuickTime: mach-o, but wrong architecture
 /System/Library/Frameworks/QuickTime.framework/QuickTime: mach-o, but wrong architecture

found a link: https://groups.google.com/forum/?fromgroups=#!topic/pyglet-users/mvvIo7NotBo

so run the command in Terminal: "defaults write com.apple.versioner.python Prefer-32-Bit -bool yes"
to set python to run in 32 bit mode
and then compile app again. no problem.

Saturday, December 01, 2012

PyQT - OpenGL - Timer


import sys
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtOpenGL import *
from PyQt4 import uic

class MyOGLWidget(QGLWidget):
    def __init__(self, parent=None):      
        QGLWidget.__init__(self, parent)
        self.spin = 0
             

    def initializeGL(self):
        print "init GL"
        glClearColor(0.0, 0.0, 0.0, 0.0);
        glShadeModel (GL_FLAT)
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.spinDisplay)
        self.timer.start(40)
        print self.timer
     

    def resizeGL(self, w, h):
        print "resize: " + str(w ) + " x " +str(h)
        glViewport(0, 0, w, h);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(-50.0, 50.0, -50.0, 50.0, -1.0, 1.0);

    def paintGL(self):
        print "paint GL"
        glClear (GL_COLOR_BUFFER_BIT );
        glPushMatrix()
        glRotatef(self.spin, 0, 0, 1)
        glColor3f (1.0, 1.0, 1.0);
        glRectf(-25.0, -25.0, 25.0, 25.0);
        glPopMatrix()
        glFlush();
     
    def spinDisplay(self):
        # print "spin display"
        self.spin = self.spin + 2
        self.spin = self.spin % 360
        # print self.spin
        #glutSwapBuffers()
        self.updateGL()
   
app = QApplication(sys.argv)
window = MyOGLWidget()
window.resize(300, 300)
window.setWindowTitle("Testing OpenGL in PyQT")
window.show()

sys.exit(app.exec_())


PyQt - OpenGL

install PyOpenGL - http://pyopengl.sourceforge.net/
install QT - http://qt-project.org/downloads
install PyQT- http://www.riverbankcomputing.com/software/pyqt/download
for Mac OS X, install PyQTX - http://sourceforge.net/projects/pyqtx/files/

import sys
from OpenGL.GL import *
from OpenGL.GLU import *
from PyQt4.QtGui import *
from PyQt4.QtOpenGL import *
from PyQt4 import uic

class MyOGLWidget(QGLWidget):
    def __init__(self, parent=None):
        QGLWidget.__init__(self, parent)      
 
    def initializeGL(self):
        print "init GL"
        glClearColor(0.0, 0.0, 0.0, 0.0);
        glShadeModel (GL_FLAT)
 
    def resizeGL(self, w, h):
        print "resize: " + str(w ) + " x " +str(h)
        glViewport(0, 0, w, h);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(-50.0, 50.0, -50.0, 50.0, -1.0, 1.0);
 
    def paintGL(self):
        print "paint GL"
        glClear (GL_COLOR_BUFFER_BIT );
        glColor3f (1.0, 1.0, 1.0);
        glRectf(-25.0, -25.0, 25.0, 25.0);
        glFlush();
     
app = QApplication(sys.argv)
window = MyOGLWidget()
window.resize(300, 300)
window.setWindowTitle("Testing OpenGL in PyQT")
window.show()

sys.exit(app.exec_())



QT designer ui in python PyQT - event


import sys
from PyQt4.QtGui import QApplication, QDialog
from PyQt4 import uic

# a sample event listener
def handle():
    print "clicked"
    # get text in QTextEdit to display in QLabel
    ui.label.setText("hello " + ui.textEdit.toPlainText())

app = QApplication(sys.argv)
window = QDialog()
# dialog.ui is an xml file generated by QT designer
ui = uic.loadUi("dialog.ui")

# set text of QTextEdit
ui.textEdit.setText("hello")
# set text with HTML
ui.textEdit.setHtml("bolditalic")
# connect an event to a listener
ui.pushButton.clicked.connect(handle)

ui.show()

sys.exit(app.exec_())


QT .UI XML

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Dialog</class>
 <widget class="QDialog" name="Dialog">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Dialog</string>
  </property>
  <widget class="QDialogButtonBox" name="buttonBox">
   <property name="geometry">
    <rect>
     <x>30</x>
     <y>240</y>
     <width>341</width>
     <height>32</height>
    </rect>
   </property>
   <property name="orientation">
    <enum>Qt::Horizontal</enum>
   </property>
   <property name="standardButtons">
    <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
   </property>
  </widget>
  <widget class="QLabel" name="label">
   <property name="geometry">
    <rect>
     <x>10</x>
     <y>10</y>
     <width>200</width>
     <height>13</height>
    </rect>
   </property>
   <property name="text">
    <string>TextLabel</string>
   </property>
  </widget>
  <widget class="QTextEdit" name="textEdit">
   <property name="geometry">
    <rect>
     <x>10</x>
     <y>30</y>
     <width>231</width>
     <height>50</height>
    </rect>
   </property>
  </widget>
  <widget class="QPushButton" name="pushButton">
   <property name="geometry">
    <rect>
     <x>10</x>
     <y>110</y>
     <width>75</width>
     <height>23</height>
    </rect>
   </property>
   <property name="text">
    <string>PushButton</string>
   </property>
  </widget>
 </widget>
 <resources/>
 <connections>
  <connection>
   <sender>buttonBox</sender>
   <signal>accepted()</signal>
   <receiver>Dialog</receiver>
   <slot>accept()</slot>
   <hints>
    <hint type="sourcelabel">
     <x>248</x>
     <y>254</y>
    </hint>
    <hint type="destinationlabel">
     <x>157</x>
     <y>274</y>
    </hint>
   </hints>
  </connection>
  <connection>
   <sender>buttonBox</sender>
   <signal>rejected()</signal>
   <receiver>Dialog</receiver>
   <slot>reject()</slot>
   <hints>
    <hint type="sourcelabel">
     <x>316</x>
     <y>260</y>
    </hint>
    <hint type="destinationlabel">
     <x>286</x>
     <y>274</y>
    </hint>
   </hints>
  </connection>
 </connections>
</ui>



Friday, November 30, 2012

Loading QT Designer .ui file in PyQT

Create .ui in QT Designer (QT Creator > New File > QT Form)


import sys
from PyQt4.QtGui import QApplication, QDialog
from PyQt4 import uic

app = QApplication(sys.argv)

# returns a QWidget subclass

# assume that dialog.ui is created from QT designer
ui = uic.loadUi("dialog.ui")
ui.show()

sys.exit(app.exec_())


Sunday, September 30, 2012

Installing Python libraries in Mac OS X

Thanks to the post in http://ashearer.com/blog/2011/xcode/ 
was trying to install Python Imaging Library (PIL), failed. 
basically from the post linked:
'enter the following command line once and the effect will last across multiple builds or installations for the remainder of the terminal session.'

export ARCHFLAGS="-arch i386 -arch x86_64"


Saturday, September 29, 2012

python + socket + xml

made a silly error:
xmldom = xml.dom.minidom.parseString(xml)
xml is a string containing the xml doc.
but its name clashes with the xml.dom.minidom package
xmldom = xml.dom.minidom.parseString(xml_string)

xml processing:
elements = xmldom.getElementsByTagName("mytag")
print elements.length                  # return number of elements
element.getAttribute("myattr")


using multiple line for code. use "\"
eg.: print "this, " + "that, " \
                + "those"

Dictionary
mydictionary = {"mykey":"hehe"}
mydictionary["newkey"] = "hello"       # can be number too
for k, v in mydictionary.iteritems():
   print k + "= " + v
if  "key" in mydictionary:
   print "key exists in dictionary"


Socket client:
import socket
socket = socket(AF_INET, SOCK_STREAM)
socket.connect(("127.0.0.1", 5000))   # address and port
data = socket.recv(4096)              # 4096 bytes buffer


binary data
data = bytearray(socket.recv(4096))
size = (data[3]<<24 | data[2]<<16 | data[1]<<8 | data[0] ) # to 32-bit or 4 byte integer


python imaging (PIL)

all thanks to the link: http://yufu.co/wordpress/?p=15

JPEG decoding from binary data using PIL. Documentation is lacking in official PIL site: http://www.pythonware.com/library/pil/handbook/image.htm

import Image
f = open("myimage.jpg", 'rb')
data = f.read()
im = Image.fromstring('RGB', (640,480), data, 'jpeg', 'RGB', '')



Monday, August 20, 2012

wxpython with new WebView

using version 2.9.4

import wx
import wx.html2

app = wx.App(False)
frame = wx.Frame(None, -1, 'A Simple Frame')
browser = wx.html2.WebView.New(frame)
browser.LoadURL("http://www.google.com")
frame.Show()
app.MainLoop()




tried loading local html file with some javascript.
worked so far. tested with jquery. ok too.

import os
browser.LoadURL(os.path.realpath("test.html"))


Tuesday, July 24, 2012

Panda3D & maya


Maya (+x, +y, +z) <=> Panda3D (+x, +z, -y)
Panda3D (+x, +y, +z) <=> Maya (+x, -z, +y)

Panda3D: camera face +Y by default; Maya: Model face +Z as Front

Sample code to add keyboard input:
        self.accept('arrow_up-up', self.moveForward ) # up cursor key released
def moveForward(self):
        self.pos = self.camera.getPos()
        self.pos.y = self.pos.y + 1
        self.camera.setPos(self.pos)
        print self.pos

Sample for mouse input:
self.accept('mouse1-up', self.click)
    
    def click(self):
        if self.mouseWatcherNode.hasMouse():
             print str(self.mouseWatcherNode.getMouseX()) + ", " + str(self.mouseWatcherNode.getMouseY()) # x and y = [-1,1], top left (-1,1), bottom right (1, -1)

Tuesday, May 22, 2012

Panda3D: Maya exporter

used maya2egg****.exe 
kept having error about "procedure entry point not located in some libmmd.dll", etc.

realised that have to copy the exe from panda/bin folder to maya/bin folder

maya2egg -a model -o "output.egg" "input.mb"


m = loader.loadModel("cube.egg")
m.reparentTo(base.render)
m.setPos(0,20,0)

EGG model loaded with texture.

couldn't get the COLLADA model to display textures.


Supported in Panda3d
Currently known scene file types are:
  Bam                             .bam
  Egg                             .egg
  MultiGen                        .flt
  Lightwave                       .lwo
  DXF                             .dxf
  VRML                            .wrl
  DirectX                         .x
  COLLADA                         .dae
  Also available: .ma .mb



Tuesday, May 15, 2012

Python & XML

how to parse XML file
using built-in xml.parsers.expat
steps:
  1. create handlers. eg.: def start_element(name, attrs):
  2. create parser. eg.: p = ParserCreate('utf-8')
  3. link handlers. eg.: p.StartElementHandler = start_element
  4. open file eg.: f = open(filename)
  5. ParseFile(file)
Python IDE summary: Netbeans 6.x looks like better choice than Eclipse in terms of code completion. however, netbeans 7 does not support python plugin. currently using netbeans 6.9.1
no problem in using Netbeans with Panda3D
discover a bug. cannot debug properly in Netbeans 6.9.1. cannot step into a method for multiple PY files. breakpoints do not work in multiple files. can be quite troublesome for debugging.
No issue with Eclipse.

converting from String to int or float using int() or float()
attributes in StartElementHandler is stored in Dictionary. eg.: to access an attribute called x , use attrs['x']

thing to note when using classes and methods, have to keep using 'self' keyword in methods when accessing object properties or methods. same as "this" in java but if you omit it in python, it will default to global variable. 

interesting note: cannot use ( ) parenthesis in "for" statement. eg.: for (x in a): 
instead use "for x in a:"

another interesting note: cannot use the same instance to re-parse another file or string. has to create a new instance of parser to do so. ie. Step 2

Sunday, November 28, 2010

python: lists

to use data structures
list
http://docs.python.org/tutorial/introduction.html#lists
a = [1, 3,4,2]
names = ['BY', 'jon']
#access individual items
eg.: a[2]
cannot use index beyond list range
so gotta use
methods: append, insert
(http://docs.python.org/tutorial/datastructures.html)
eg.: a.append(1000)
to find size of list: len(a)

Tuesday, September 08, 2009

maya + python: UI


cubeHt = 2
rgb = [0.5, 0.5, 0.5]

# functions
def updateSlider(*args):
intSlider(slider, value = int(args[0]), e=True);
def updateTxt(*args):
intField(txt, value = int(args[0]), e=True);
def buttonPush(*args):
print(str(args))
n = intField(txt, q=True, value=True)
createCubes(n)
def createCubes(n):
i=0
while(i<n):
names = polyCube();
move((i-n/2)*2, cubeHt, 0, names[0]);
#apply material
sets( names[0], e=True, forceElement=shadingGroup[0] )
i= i+1
def newFile(*args):
init()
def colorUpdate(*args):
rgb = colorSliderGrp(color, q=True, rgb=True)
print(shadingGroup[1])
setAttr(shadingGroup[1]+".diffuse" , rgb[0], rgb[1], rgb[2], type='double3' ) ;

def createMaterials():
# set up ambient occlusion for mental ray
material = shadingNode('mib_illum_lambert', asShader=True)
texture = shadingNode('mib_amb_occlusion', asShader=True)
connectAttr(texture + '.outValue', material + '.ambient', f=True );

# set up shading group, connect material to this group and apply group to cube object
group = sets( renderable=True, empty=True )
connectAttr( material+".outValue", group+".miMaterialShader", force=True)
setAttr(material+".ambience", 0.5, 0.5, 0.5, type='double3' ) ;
setAttr(material+".diffuse" , 0.5, 0.5, 0.5, type='double3' ) ;
result = [group, material, texture]
return result
def createPlane():
names = polyPlane( w=20, h=20)
white = createMaterials()
sets( names[0], e=True, forceElement=white[0] )
def init():
# new file
file(new=True, force=True)
# create a plane
createPlane()
shadingGroup = createMaterials()

init()
result = promptDialog(
title='Welcome',
message='Enter Name:',
button=['OK', 'Cancel'],
defaultButton='OK',
cancelButton='Cancel',
dismissString='Cancel')

if (result == 'OK'):
name = promptDialog(query=True, text=True)
confirmDialog( title='Welcome', message='Welcome, ' + name, button=['OK'] )


# create a window
w = 400
h = 240
win = window( title="Boon's UI", iconName='TBY', widthHeight=(w, h) )
c1 = columnLayout( columnAttach=('both', 5), rowSpacing=5, adjustableColumn=True )
r1 = rowLayout( numberOfColumns=3, parent=c1)
text( label='Number of cubes')
txt = intField(value=1, changeCommand=updateSlider)
slider = intSlider(min=0, max=10, value=1, step=1, changeCommand=updateTxt)
color = colorSliderGrp( parent=c1, label='Color of cube', rgb=(1, 1, 1) ,changeCommand=colorUpdate)
button(parent=c1, label='Create cubes', command=buttonPush )
button(parent=c1, label='New File', command=newFile )
showWindow(win)


Sunday, September 06, 2009

maya + python: mental ray nodes

# set up ambient occlusion for mental ray
material = shadingNode('mib_illum_lambert', asShader=True)
texture = shadingNode('mib_amb_occlusion', asShader=True)
connectAttr(texture + '.outValue', material + '.ambient', f=True );

# set up shading group, connect material to this group and apply group to cube object
group = 'mibMaterialGroup'
sets( name=group, renderable=True, empty=True )
connectAttr( material+".outValue", group+".miMaterialShader", force=True)
sets( cube, e=True, forceElement=group )
setAttr(material+".ambience", 0.5, 0.5, 0.5, type='double3' ) ;
setAttr(material+".diffuse" , 0.5, 0.5, 0.5, type='double3' ) ;

Friday, September 04, 2009

python+maya: animation

from maya.cmds import *
import random
import math

# Delete any existing scene
file(newFile=True, force=True)

names = sphere(r=10)
s = names[0] # object name
# call python script procedure haha() in anim.py module
expression(o=s, s='python("anim.haha()")', ae=True)
playbackOptions( minTime='0sec', maxTime='10sec', loop='continuous')
play( state=True )
viewFit()

# create a function to run every frame
def haha():
x = getAttr(s + ".translateX")
#print(x)
t = currentTime(query=True)
#print(t)
x = 50* math.cos(math.pi * t / 120)
# setAttr(s + ".translateX", x);
setAttr(s + ".translate", x, 0, 0);


Apparently, must Bake Simulation before rendering. no dynamic content when rendering
Edit > Keys > Bake Simulation

Strange. some bug. in Render option > Common > End Frame. if i key in 240, it will reset to 10. but if i key in 100 first, it will accept. and then 240, it will accept. ???