Sunday, December 30, 2007

XUL and Python

You can use Python with XUL with the help of a http server
which execute plain Python Scripts sent by the client.
Like the following :
CPython Server
<?xml version="1।0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<window id="example-window" title="Example 7.2.1"
xmlns:html="http://www.w3.org/1999/xhtml"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

<script language="javascript">

var wmi=" \n\
import wmi \n\
c = wmi.WMI('Python') \n\
for os in c.Win32_OperatingSystem(): \n\
caption = os.Caption \n\
response = caption \n\
filename = 'foo'"

function WebMethod(url,request,callback)
{
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
} catch (e) {
alert("Permission UniversalBrowserRead denied.");
}

var http = new XMLHttpRequest();
var mode = request?"POST":"GET";
http.open(mode,url,true);
if(mode=="POST"){http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');}
http.onreadystatechange=function(){if(http.readyState==4){callback(http.responseText);}};
http.send(request);
}

function CallBack(r)
{
alert(r);
}

</script>
<box id="aBox" width="200">
<button label="GetOsName" oncommand="WebMethod('http://127.0.0.1:9981',wmi,CallBack);"/>
</box>
</window>

Thursday, December 27, 2007

WMI - Mochikit


&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;
&lt;html&gt;
&lt;head&gt;
&lt;style type="text/css"&gt;
table.prettytable thead,th,tfoot
{
background-color : #676789;
text-align : center;
font-weight: bold;
color: #fff;
}
table.prettytable
{
border: 1px solid black;
}

&lt;/style&gt;
&lt;script type="text/javascript" src="../../lib/MochiKit/MochiKit.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;

result = []

row_display = function (row)
{
return TR(null, map(partial(TD, null), row));
}

function getDiskInfo()
{
var loc = new ActiveXObject("WbemScripting.SWbemLocator");
var wmi = loc.ConnectServer("", "root\\cimv2");
var ins = wmi.ExecQuery("select * from Win32_LogicalDisk");
for (var col = new Enumerator(ins);!col.atEnd();col.moveNext())
{
var disq = col.item()
result.push([disq.DeviceId,disq.FreeSpace,disq.Size])
}

var newTable = TABLE({'class': 'prettytable'},
THEAD(null,row_display(["Name", "FreeSpace", "Size"])),
TFOOT(null,row_display(["foot1", "foot2", "foot3"])),
TBODY(null,map(row_display, result)));

appendChildNodes("theBody",newTable);

}
&lt;/script&gt;
&lt;/head&gt;
&lt;body id="theBody" onload="getDiskInfo()"&gt;

&lt;/body&gt;
&lt;/html&gt;



Powered by ScribeFire.

Wednesday, December 26, 2007

wmi - IronPython


import System
import clr
clr.AddReference("System.Management")
import System.Management

def requestWMI(squery,sproperties):
output = ""
objMgt = System.Management.ManagementObjectSearcher(squery)
for result in objMgt.Get():
output += result.GetPropertyValue(sproperties)
return output

print requestWMI("Select * from Win32_BIOS", "Caption")
raw_input()


Powered by ScribeFire.

Tuesday, December 18, 2007

JScript .NET + WMI

Finding documentation for using WMI with JScript is not easy.
Compile this code with 'jsc' (shipped with .Net) in an exe file

import System;
import System.Management;

var diskSearch = new ManagementObjectSearcher("Select * from Win32_LogicalDisk")
var obj = diskSearch.Get()
var prop = new Object()

for (prop in obj){
print(prop['Caption'])
}


Powered by ScribeFire.

Monday, November 26, 2007

VBS from Python


from win32com.client import Dispatch


#ref : http://mow001.blogspot.com/2006/03/vbscript-hosting-in-msh-inputbox-in.html

vbs = Dispatch("MSScriptControl.ScriptControl")
vbs.Language = "vbscript";

wmi= r"""
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery( _
"SELECT Caption,Size FROM Win32_LogicalDisk where drivetype='3'",,48)
"""

ldisque = []



def cleanString(s):
car = [';','"','\n','\t',' ']
for c in car:
try:
s = s.replace(c,'')
except:
continue
head = s.index('{')
tail = s.index('}')
s = s.replace(':',',')
s = s.replace('=',':')
return s


vbs.addcode(wmi)
col = vbs.eval('colItems')


for item in col:
disque = item.GetObjectText_()
print cleanString(disque)



vbs = None

Calling VBS from Python

from win32com.client import Dispatch


#ref : http://mow001.blogspot.com/2006/03/vbscript-hosting-in-msh-inputbox-in.html

vbs = Dispatch("MSScriptControl.ScriptControl")
vbs.Language = "vbscript";


code = """
function Input()
Input = inputbox("message","titre")
end function

function add(x,y)
add = x + y
end function
"""

vbs.addcode(code)

txt = vbs.eval('Input()')
print txt

somme = vbs.eval('add(2,3)')

vbs.ExecuteStatement('msgbox "The result is %d",,"Call VBS Add from Python"'%somme)



Powered by ScribeFire.

Tuesday, November 20, 2007

wxPython - TreeControl - SplitPanel


# -*- coding: iso-8859-1 -*-

# Référence : wxPython in Action from Robin Dunn - Noel Rappin


import os
import wx

ID_ABOUT = wx.NewId()
ID_OPEN = wx.NewId()
ID_EXIT = wx.NewId()


tree = [
['Dakar',
['Administration',
['Supervision',
['Disques','Banques','File d''attentes']],
'Réseaux'],
], #/Dakar
['Denver',
['Administration','Supervision','Réseaux'],
] #/Denver
]

class TreeServeur(wx.TreeCtrl):
def __init__(self, parent,id):
super(TreeServeur, self).__init__(parent,id)
self.Bind(wx.EVT_TREE_ITEM_EXPANDING, self.OnExpandItem)
self.Bind(wx.EVT_TREE_ITEM_COLLAPSING, self.OnCollapseItem)
self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivated)

root = self.AddRoot("Serveurs")
self.AddTreeNodes(root,tree)

def AddTreeNodes(self, parentItem, items):
for item in items:
if type(item) == str:
self.AppendItem(parentItem, item)
else:
newItem = self.AppendItem(parentItem, item[0])
self.AddTreeNodes(newItem, item[1])

def OnExpandItem(self, evt):
pass

def OnCollapseItem(self,evt):
pass

def OnActivated(self,evt):
print "OnActivated: ", self.GetItemText(evt.GetItem())


class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(1024, 800))

self.initpos = 50

#Status Bar
self.CreateStatusBar()

#Menu Fichier
filemenu = wx.Menu()
filemenu.Append(ID_OPEN,'&Ouvrir')
filemenu.Append(ID_EXIT,'&Quitter')
#Menu Aide
aidemenu = wx.Menu()
aidemenu.Append(ID_ABOUT,'&Aide')
#Barre de Menu
menubar = wx.MenuBar()
menubar.Append(filemenu,'&Fichier')
menubar.Append(aidemenu,'&Aide')
self.SetMenuBar(menubar)
#Gestionnaire d'evenement menu
wx.EVT_MENU(self, ID_ABOUT, self.OnAbout)
wx.EVT_MENU(self, ID_EXIT, self.OnExit)
wx.EVT_MENU(self, ID_OPEN, self.OnOpen)

#Splitter
splitter1 = wx.SplitterWindow(self, -1, style=wx.SP_3D)
splitter1.SetMinimumPaneSize(200)
splitter1.SetSashPosition(40)
splitter1.UpdateSize()
splitter2 = wx.SplitterWindow(splitter1, -1, style=wx.SP_3D)
splitter2.SetMinimumPaneSize(50)
splitter2.SetSashPosition(40)

self.sidebar = TreeServeur(splitter1, id=-1)

self.up =wx.TextCtrl(splitter2, wx.NewId(), "Un texte", size=(100, -1),pos=(80, 50))
self.down = wx.ListCtrl(splitter2, -1, style=wx.LC_LIST)

splitter1.SplitVertically(self.sidebar, splitter2,200)
splitter2.SplitHorizontally(self.up, self.down,0)

self.Centre()

def OnActivated(self,evt):
print "OnActivated: ", self.GetItemText(evt.GetItem())

def ShowMessage(self,msg):
d = wx.MessageDialog(self, msg, style=wx.OK)
d.ShowModal()
d.Destroy()

def OnAbout(self, event):
self.ShowMessage("About")

def OnExit(self,e):
self.Close(True)

def OnOpen(self,e):
#Ouverture d'un fichier"
self.dirname = ""
wildcard = "*.py"
dlg = wx.FileDialog(
self, message="Choose a file",
defaultDir=os.getcwd(),
defaultFile="",
wildcard=wildcard,
style=wx.OPEN | wx.MULTIPLE | wx.CHANGE_DIR
)
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
f = open(path)
self.control.SetValue(f.read())
dlg.Destroy()

class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, "dragdrop.py")
frame.Show(True)
self.SetTopWindow(frame)
return True

app = MyApp(redirect=False)
app.MainLoop()


Wednesday, November 7, 2007

Python : HTA


<html>
<head>
<TITLE>HTML Application Example</TITLE>
<HTA:APPLICATION ID="HTAEx" APPLICATIONNAME="HTAEx" ICON="e.ico" WINDOWSTATE="normal">
<style type="text/css">

body {
background-color:#fff;
}

.blank{
color:#ffffff;
}

select {
font-size:0.8em;
font-weight: bold;
text-align:center;
padding:15px;
}

#info {
text-align:left;
background-color: #000;
color: #fff;
padding-left: 5px;
font-size:1em;
}

.patience {
background-color:#ccccee;
width=100%;
text-align:center;
color: #000000;
font-weight: bold;
}


.pair{
background-color: #ccccee;
}

.impair{
background-color: #ffccff;
}

.detail {
padding-right: 10px;
padding-left: 6px;
text-align: right;
}

.Ink {

position: absolute;

background-color: #fff;

border-top: 1px solid transparent;

width: 1px;

height: 1px;

}


</style>

<body onLoad="Initialisation()">
<center><h2>Système d'Administration Simplifié</h2></center>
<table align="center" width="80%" style="border:0px solid black; margin-top:40px;">
<tr><td id="message" style="visibility:hidden;flush="true"">TEST</td></tr>
<tr><th style="background-color:#000;color:#fff;">Serveurs</th><th><div id="info">Informations</div></th></tr>
<tr>
<td width="220px" valign="top">
<div id="tabgauche">
<select size="1" name="liste" onChange="selectServeur()">
<option selected="selected" value="None" class="blank">-----------------------------------------</option>
<option value="1" class="opts">&nbsp;Dakar</option>
<option value="2" class="opts">&nbsp;Denver</option>
<option value="3" class="opts">&nbsp;Douala</option>
<option value="4" class="opts">&nbsp;Dublin</option>
<option value="NONE" class="opts"><hr /></option>
<option value="5" class="opts">&nbsp;Fatima</option>
<option value="6" class="opts">&nbsp;Flores</option>
<option value="7" class="opts">&nbsp;Francfort</option>
<option value="8" class="opts">&nbsp;Fresno</option>
<option value="NONE" class="opts"><hr /></option>
<option value="9" class="opts">&nbsp;Python - 127.0.0.1</option>
</select>
</div>
</td>
<td valign="top">
<div id="tabcentreInfo"></div>
</td>
</tr>
<tr><td colspan="2"><hr /></td></tr>
<tr>
<td valign="top" style="background-color:#fff;">
<div id="svc">&nbsp;</div>
</td>
<td valign="top">
<div id="tabcentre">&nbsp;</div>
</td>
</tr>
</table>
<div id="espace"></div>
<!-- Script -->

<script language=Python>

from win32com.client import GetObject,Dispatch
import pythoncom
import win32gui
import os
import thread
import win32api
import locale
import Image,ImageDraw
import cStringIO
from random import randint as rint
import base64

locale.setlocale(locale.LC_NUMERIC, '')

serveurs = {}
services = {}
cmd ={}

Serveur = None
LstService = None
IdServeur = None
Busy = 0

serveurs[1] = ['Dakar']
serveurs[2] = ['Denver']
serveurs[3] = ['Douala']
serveurs[4] = ['Dublin']
serveurs[5] = ['Fatima']
serveurs[6] = ['Flores']
serveurs[7] = ['Francfort']
serveurs[8] = ['Fresno']
serveurs[9] = ["Python"]

svcsysteme = ['systeme','Param&egrave;tre Syst&egrave;me']
svcbanque = ['banque','Etat des Banques']
svcdisque = ['disque','Espace Disque']
svcstream = ['stream','Streaming']

#Dakar
services[1] = [svcsysteme,svcbanque]
#Denver
services[2] = [svcsysteme,svcbanque]
#Douala
services[3] = [svcsysteme,svcbanque]
#Dublin
services[4] = [svcsysteme,svcbanque]

#Fatima
services[5] = [svcsysteme,svcbanque]
#Flores
services[6] = [svcsysteme,svcbanque]
#Francfort
services[7] = [svcsysteme,svcbanque]
#Fresno
services[8] = [svcsysteme,svcbanque]
#Python
services[9] = [svcsysteme,svcdisque,svcstream]

#Gestion Mouse
def Pointer():
document.body.style.cursor = "hand"
return

def DefaultCursor():
document.body.style.cursor = "default"
return

def WaitCursor():
win32gui.PumpWaitingMessages()
document.body.style.cursor = "wait"
return


#Gestion DIV
def getValue(id):
#return document.getElementById(id).value
return document.getElementById(id).getAttribute("value")

def getElt(id):
return document.getElementById(id)

def setValue(divid,data):
elt = document.getElementById(divid)
elt.innerHTML = data

def showMessage(message="info"):
elt = getElt("message")
elt.innerHTML = message
elt.style.visibility = "visible"
return 1
elt = getElt("message")
elt.style.visibility = "hidden"

def majTabInfo():
elt = getElt('tabcentreInfo')
serveur = serveurs[IdServeur][0]
elt.innerHTML = """<span onClick="connectServer('%s')"
onmouseover='Pointer()'
onmouseout='DefaultCursor()'>
<b>Se connecter</b></span>"""%(serveur)


def groupLstByN(l,n,filter=None):
#group elt in l by n
res = []
k = 0
lp = []
for elt in l:
lp.append(elt)
k +=1
if k == n:
k = 0
res.append(lp)
lp = []
return [tuple(item) for item in res]


def number_format(num, places=0):
s = locale.format("%.*f", (places, num), True)
return s.replace('\xa0',' ')


def formatTable(titre,data):
"""
titre = ["t1",t2"]
data = [["a","b"],["1","2"]]
"""
table = "<table border='1'>"
n = len(titre)
th = r"<th>%s</th>"*n
td = "<td class='detail'>%s</td>"*n
coltitre = th%(tuple(titre))
table += coltitre
i = 0
for item in data:
if i%2 == 0:
table += ("<tr class='pair'>"+td%(tuple(item))+"</tr>")
else:
table += ("<tr class='impair'>"+td%(tuple(item))+"</tr>")
i += 1
return table + "</table>"

def randgradient():
img = Image.new("RGB", (300,300), "#FFFFFF")
draw = ImageDraw.Draw(img)

r,g,b = rint(0,255), rint(0,255), rint(0,255)
dr = (rint(0,255) - r)/300.
dg = (rint(0,255) - g)/300.
db = (rint(0,255) - b)/300.
for i in range(300):
r,g,b = r+dr, g+dg, b+db
draw.line((i,0,i,300), fill=(int(r),int(g),int(b)))

f = cStringIO.StringIO()
img.save(f, "PNG")

print "Content-type: image/png\n"
f.seek(0)
return f


# Procédures de service

cmdDisk = r'wmic /Node:%s path win32_logicaldisk WHERE "DriveType=3" GET DeviceID,Freespace,Size '


def infoBanque():
alert("Banque")

def setPauseMsg(started=0):
if started == 1:
WaitCursor()
setValue("tabcentreInfo","<span class='patience'>Veuillez Patienter....</span>")
else:
Pointer()
majTabInfo()
win32gui.PumpWaitingMessages()

def infoSysteme():
setPauseMsg(1)
for i in range(10000):
i = i
titre = ["a","b"]
data = [[1,2],[2,4]]
content = formatTable(titre, data)
setValue("tabcentre",content)
setPauseMsg(0)

def infoDisque():
#cmd: cmdDisk
setPauseMsg(1)
setValue("tabcentre","")
titrecols = ['Nom','Espace Libre','Espace Total','Pourcentage']
c = os.popen(cmdDisk%Serveur).readlines()[1:-1]
items = [item.strip().split() for item in c]
for item in items:
percent = (1 - 1.0*long(item[1])/long(item[2]))*100
item.append("%.2f"%percent+"%")
item[1] = number_format(long(item[1]), 0)
item[2] = number_format(long(item[2]), 0)
# setValue("tabcentre",`items`)
content = formatTable(titrecols,items)
setValue("tabcentre",content)
setPauseMsg(0)

i = 0
def counter():
global i
i += 1
setValue("tabcentre",i)

intcounter = 0
def infoStream():
global intcounter
intcounter = window.setInterval('counter()',500)

#Fin des procédures de service

cmd['systeme'] = infoSysteme
cmd['banque'] = infoBanque
cmd['disque'] = infoDisque
cmd['stream'] = infoStream


def Initialisation():
pass

def majService():
menu = "<ul>"
for item in LstService:
menu += "<li id=%s onmouseover='Pointer()',\
onmouseout='DefaultCursor()',\
onClick='getMenuOption(%s)'>%s</li>"%(item[0],\
LstService.index(item),item[1])
menu += "</ul>"
setValue('svc',menu)

def clearZoneInfo():
elt = getElt('info')
elt.innerHTML = "Informations"

def clearCentre():
elt = getElt('tabcentre')
elt.innerHTML = ""

def connectServer(serveur):
os.system("mstsc -v %s"%serveur)

def getMenuOption(args):
window.clearInterval(intcounter)
global selectedService
service = services[IdServeur][args][0]
libelle = services[IdServeur][args][1]
selectedService = service
elt = getElt('info')
elt.innerHTML = libelle
try:
cmd[service]()
except:
pass

def clearInfo():
clearZoneInfo()
clearCentre()
setValue('tabcentre','')
setValue('svc','')

def selectServeur():
global Serveur, LstService, IdServeur
clearInfo()
try:
IdServeur = int(getValue('liste'))
except:
return
try:
Serveur = serveurs[IdServeur][0]
LstService = services[IdServeur]
majService()
majTabInfo()
except:
return
DefaultCursor()

</script>
</body>
</html>

Thursday, November 1, 2007

Python : Command Line Options

from optparse import *
from optparse import OptionParser
import sys

def mycall(option, opt, value, parser):
    print "Vous n'avez pas ce privilège"
    sys.exit()

def main():
    utilisation = "utilisation : %prog [options] arg]"
    parser = OptionParser(utilisation)
    parser.add_option("-f", "--fichier", dest="fichier",help="Lit a prtie d'un fichier")
    parser.add_option("-d", action="callback", callback = mycall)
    parser.add_option("-m", "--mois", dest="mois",help="Moise saisie")
    parser.add_option("-v", "--verbeux",action="store_true", dest="verbeux")
    parser.add_option("-s", "--sauvegarde", action="store_true", dest="sauvegarde")
    (options, args) = parser.parse_args()
    print "Fichier : %s, Mois : %s, Sauvegarde : %s"%(options.fichier,options.mois,options.sauvegarde)

Sunday, October 7, 2007

Boo - Asynchronous call

import System
import System.Collections
import System.Threading
import System.Net

def callback(result as IAsyncResult):
    print("callback")
    
def run():
    print "Executing"
    
print("started")

result = run.BeginInvoke(callback, null)
System.Threading.Thread.Sleep(50ms)
run.EndInvoke(result)

print ("done")

request = WebRequest.Create("http://www.python.org/")

result = request.GetResponse.BeginInvoke(null, null)
while not result.IsCompleted:
    Console.Write("!")
    Thread.Sleep(25ms)
Console.WriteLine()

// ready to get the response
response = request.GetResponse.EndInvoke(result)

Console.WriteLine("${response.ContentLength} bytes.")

print "Press any key to continue . . . "
Console.ReadKey(true)

Boo and WMI

namespace wmi

import System
import System.Management
import System.Collections

query =  """SELECT * FROM Win32_LogicalDisk  
            where drivetype=3"""

searcher = ManagementObjectSearcher("root\\CIMV2",query)
results = searcher.Get()

for b as ManagementObject in results:
    print b.Properties["DeviceID"].Value,b.Properties["Size"].Value

print "Press any key to continue . . . "
Console.ReadKey(true)

Thursday, September 13, 2007

wmic : un secret bien gardé

Cela fait maintenant un petit moment que travaille sous Windows, et je viens à peine
de découvrir cet outil surpuissant.Je vous engage à vous y intéresser.

Voici par exemple comment ouvrir une console 'cmd' sur un hôte distant

C:\Documents and Settings\artyprog&gt;wmic /node:192.168.12.1 process call create 'cmd.exe'

Je vous laisse découvrir le reste :-)


Saturday, July 28, 2007

Python - HTA : Capturer la position de la Souris

Cet exemple montre comment capturer la position de la souris en Python

Article de référence :
http://msdn2.microsoft.com/en-us/library/ms531073.aspx

<HTML>
<HEAD><TITLE>Report mouse moves in Python</TITLE>

<BODY onmousemove="reportMove()">
<H1>Python catch the Mouse</H1>

<div id="pos"></div>

<SCRIPT LANGUAGE="Python">
d = document.all
def reportMove():
x = window.event.x
y = window.event.y
d.pos.innerHTML = "posx = %d, posy =%d"%(x, y)
</SCRIPT>

</BODY>
</HTML>

Python - HTA : Simple Wizard


Voici comment afficher des pages contenues dans de simples fichiers texte.
Très pratique pour écrire par exemple, des assistants


Fichier tutorhta.txt (servant dans le script tutor.hta)

%pywizard%
%
<h1>Introduction</h1>
D'apr&egrave;s l'article de microsoft :
<a href="http://msdn2.microsoft.com/en-us/library/bb264002.aspx">Getting Your Page's Data into a Bind</a>
%
%
<h2>Chapitre 1</h2>
%
%
<h2>Chapitre 2</h2>
%

fichier tutor.hta

<html>
<head>
<OBJECT ID="Content" WIDTH=0 HEIGHT=0
CLASSID="CLSID:333C7BC4-460F-11D0-BC04-0080C7055A83">
<PARAM NAME="TextQualifier" VALUE="%">
<PARAM NAME="FieldDelim" VALUE="|">
<PARAM NAME="DataURL" VALUE="tutorhta.txt">
<PARAM NAME="UseHeader" VALUE="true">
</OBJECT>
</head>
<body style="font-family: verdana">

<span style="font-weight: bold; cursor: hand" onclick="goBackward()"><<</span>
Python - HTA
<span style="font-weight: bold; cursor: hand" onclick="goForward()">>></span>
<br>
<span id=Status></span><br>
<div id=TheStory datasrc=#Content datafld="pywizard" dataformatas="HTML"></div>

<SCRIPT language=Python>

doc = document.all
rs = None

def goForward():
global rs
if (rs.absolutePosition != rs.recordCount) :
rs.MoveNext()
else :
rs.MoveFirst()

def goBackward():
global rs
if (rs.absolutePosition > 1) :
rs.MovePrevious()
else :
rs.MoveLast()

def initialize():
global rs
rs=doc.Content.recordset;


window.onload = initialize()

</SCRIPT>
</body>
</html>

Thursday, July 19, 2007

HTA - Python : Gestionnaire de Tâches


<html>
<head>
<title>Python Process Lister</title>
<HTA:APPLICATION
ID="processlister"
APPLICATIONNAME="Python Process Lister"
SCROLL="auto"
SCROLLFLAT = "yes"
SINGLEINSTANCE="yes"
>

<style type="text/css">

body {
background-color: #ababcd;
font-family: Verdana
font-size: 0.9 em;
color: #fff;
}

a:link {text-decoration: none; color:#343456}
a:visited {text-decoration: none;color:#343456}
a:active {text-decoration: none; color:#343456}
a:hover {text-decoration: underline; color:452200;}

</style>
</head>


<body onLoad="Initialisation()">
<center><h2>Liste des Process</h2></center>
<span id = "ProcessList"></span>


<!-- Script Python -->
<SCRIPT LANGUAGE="Python">
from win32com.client import GetObject
import win32gui

doc = document.All

ChaineConnexion = r"WinMgMts:\\%s\%s"

listProcess = []

process = None

def displayProc(args):
proc = None
numproc = int(args)
rep = window.confirm("Voulez-vous terminer le processus %s ?"%args )
if rep:
for p in process:
proc = p
if int(p.Handle) == numproc:
alert(u"Le processus %d va être supprimé"%numproc)
break
proc.Terminate

def getAllObjects(serveur = ".", espaceDenom = "root\cimv2", classe = "Win32_Process"):
c = GetObject(ChaineConnexion%(serveur,espaceDenom))
objects = c.ExecQuery(r"select * from %s"%classe)
return objects

def Initialisation():
win32gui.MessageBox(0, " Hello From Python", "Message d'Invite", 0)
RefreshList()
iTimerID = window.setInterval("RefreshList()", 10000)

def RefreshList():
global process

process = getAllObjects()

result = "<table>"
for processus in process:
result += """<tr><td align="right">%4d</td>
<td style="padding-left:15px;"><a class="maya" href="#" onClick="displayProc(%d)">%s</a></div></td>
<td>%s</td>
</tr>"""%(int(processus.Handle),int(processus.Handle),processus.Name,processus.CommandLine)

result += "</table>"

doc.ProcessList.InnerHTML = result

</SCRIPT>

</body>
</html>

Sunday, July 15, 2007

HTA : Arguments en ligne de commande


<HTML>

<HEAD>

<TITLE>HTA Demo</TITLE>
<HTA:APPLICATION ID="oHTA"
APPLICATIONNAME="myApp"
BORDER="thin"
BORDERSTYLE="normal"
CAPTION="yes"
ICON=""
MAXIMIZEBUTTON="yes"
MINIMIZEBUTTON="yes"
SHOWINTASKBAR="no"
SINGLEINSTANCE="no"
SYSMENU="yes"
VERSION="1.0"
WINDOWSTATE="maximize"/>

<SCRIPT language="Python">
d = document.all
lienMSN = "http://msdn2.microsoft.com/en-us/library/ms536495.aspx"
def window_onload():
sTempStr = "applicationName = " + d.oHTA.applicationName + "<br />"
sTempStr += "commandLineName = " + d.oHTA.commandLine + "<br />"
d.oPre.innerHTML = '<a href="%s">%s</a>'%(lienMSN,lienMSN) + "<br />" + sTempStr

</SCRIPT>

</HEAD>

<BODY SCROLL="no">

<p>Les arguments doivent suivre le nom du script et être entourés de guillemets</p>
<PRE ID=oPre></PRE>

</BODY>

</HTML>

Python et WMI

WMI (Windows Managment Instrumentation) est un ensemble de classes permettant d'auditer des serveurs Windows.
L'accés à ces classe est très aisée en Python comme le montre cet exemple:


from win32com.client import GetObject

ChaineConnexion = r"WinMgMts:\\%s\%s"

def getAllObjects(serveur = ".", espaceDenom = "root\cimv2", classe = "Win32_Process"):
c = GetObject(ChaineConnexion%(serveur,espaceDenom))
objects = c.ExecQuery(r"select * from %s"%classe)
return objects

def test():
allObj = getAllObjects()
for proc in allObj:
print proc.Name

if __name__ == "__main__":
test()

Thursday, July 12, 2007

Python et HTA

Python peut parfaitement être utlisé dans les scripts HTA.
Ce qui est un avantage indéniable par rapport à l'utilisation de vbscript.


<html>
<head>
<TITLE>HTML Application Example</TITLE>
<HTA:APPLICATION ID="HTAEx" APPLICATIONNAME="HTAEx" ICON="e.ico" WINDOWSTATE="normal">
</head>

<body onLoad="Initialisation()">
<center><h1>Python in HTML Application</h1></center>

<FORM>
<INPUT TYPE="text" name="gauche">
<INPUT TYPE="button" name="gbutton" value = "MAJ Gauche">
</FORM>

<FORM>
<INPUT TYPE="text" name="centre">
<INPUT TYPE="button" name="cbutton" value = "MAJ Centre">
</FORM>

<FORM>
<INPUT TYPE="text" name="droite">
<INPUT TYPE="button" name="dbutton" value = "MAJ Droite">
</FORM>

<table width="100%" border=0>
<tr>
<td width="33%" valign="top" border= "black"><div id="tabgauche">&nbsp;</div></td>
<td width="33%" valign="top"><div id="tabcentre">&nbsp;</div></td>
<td width="33%" valign="top"><div id="tabdroite">&nbsp;</div></td>
</tr>
</table>

<div id="espace"></div>

S&eacute;lectionnez une option :<br />
<select size="3" name="liste" onChange="SelectOption()">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>


<!-- Script -->

<script language=Python>

import win32gui
import os


def GetValue(id):
#return document.getElementById(id).value
return document.getElementById(id).getAttribute("value")

def Initialisation():
win32gui.MessageBox(0, " Hello From Python", "Message d'Invite", 0)
d = document.getElementById('espace')
sp = "&nbsp;"*5
d.innerHTML = sp

def SelectOption(*args):
option = GetValue('liste')
win32gui.MessageBox(0, "Option : %s"%option, "Valeur de la Selection", 0)

def gbutton_Onclick():
valeur = GetValue('gauche')
div = document.getElementById('tabgauche')
div.innerHTML = valeur

def cbutton_Onclick():
valeur = GetValue('centre')
div = document.getElementById('tabcentre')
div.innerHTML = valeur

def dbutton_Onclick():
valeur = GetValue('droite')
div = document.getElementById('tabdroite')
div.innerHTML = valeur

</script>
</body>
</html>

Les Scripts HTA


Les applications 'hta' sont de simples fichiers html ayant pout extension 'hta'.
Leur intérêt, entre autre, est qu'il sont interprétes par Windows comme de véritables
applications. Ils permettent ainsi l'utilisation de tous les composants 'html' dans les
scripts écrits en vbscript ou tout autre langage supporté par wsh.


<html>
<head>
<title>Running a Script from Text</title>
<HTA:APPLICATION
ID="objScriptFromText"
APPLICATIONNAME="Running a Script from Text"
SCROLL="auto"
SINGLEINSTANCE="yes"
>
</head>

<SCRIPT Language="VBScript">

Sub RunScript
Msgbox "The script has run."
End Sub

Sub Pointer
document.body.style.cursor = "hand"
End Sub

Sub DefaultCursor
document.body.style.cursor = "default"
End Sub

</SCRIPT>

<body bgcolor="buttonface">

<span id="ClickableSpan" onClick="RunScript" onmouseover="Pointer"
onmouseout="DefaultCursor">
Click here to run the script</span>

</body>
</html>

Tuesday, June 5, 2007

XNA - Boo

Voci un exemple pour Boo, adapté de C# par Cédric Vidier.

Voci un exemple pour Boo, adapté de C# par Cédric Vidier.


namespace SimpleExample

import System
import System.Collections.Generic
import Microsoft.Xna.Framework
import Microsoft.Xna.Framework.Audio
import Microsoft.Xna.Framework.Content
import Microsoft.Xna.Framework.Graphics
import Microsoft.Xna.Framework.Input
import Microsoft.Xna.Framework.Storage


///
/// When run, you'll see an empty blue screen. This code can
/// be run in both Mono.Xna and Microsoft XNA without changing
/// any code.
///

class SimpleExampleGame(Microsoft.Xna.Framework.Game):
graphics as GraphicsDeviceManager
content as ContentManager

def constructor():
graphics = GraphicsDeviceManager(self)
content = ContentManager(Services)


/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.

protected override def Initialize():
// TODO: Add your initialization logic here
super()


/// Load your graphics content. If loadAllContent is true, you should
/// load content from both ResourceManagementMode pools. Otherwise, just
/// load ResourceManagementMode.Manual content.

/// Which type of content to load.
protected override def LoadGraphicsContent(loadAllContent as bool):
if loadAllContent:
// TODO: Load any ResourceManagementMode.Automatic content
pass
// TODO: Load any ResourceManagementMode.Manual content


/// Unload your graphics content. If unloadAllContent is true, you should
/// unload content from both ResourceManagementMode pools. Otherwise, just
/// unload ResourceManagementMode.Manual content. Manual content will get
/// Disposed by the GraphicsDevice during a Reset.

/// Which type of content to unload.
protected override def UnloadGraphicsContent(unloadAllContent as bool):
if unloadAllContent:
content.Unload()


/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input and playing audio.

/// Provides a snapshot of timing values.
protected override def Update(gameTime as GameTime):
// Allows the default game to exit on Xbox 360 and Windows
if GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed:
Exit()

// TODO: Add your update logic here
super(gameTime)


/// This is called when the game should draw itself.

/// Provides a snapshot of timing values.
protected override def Draw(gameTime as GameTime):
graphics.GraphicsDevice.Clear(Color.CornflowerBlue)

// TODO: Add your drawing code here
super(gameTime)

Sunday, June 3, 2007

XNA - IronPython

IronPython et la version du célèbre langage (mon favori en fait) porté sur la plateforme .NET.
Xna et le framework de développement de jeux pour XBOX et Windows .Net. Voici un petit exemple écrit par Leaf:


import clr
clr.AddReference('Microsoft.Xna.Framework')
clr.AddReference('Microsoft.Xna.Framework.Game')

from Microsoft.Xna.Framework import *
from Microsoft.Xna.Framework.Graphics import *
from Microsoft.Xna.Framework.Content import *

class MyGame(Game):
def __init__(self):
self.spriteX = self.spriteY = 0
self.spriteSpeedX = self.spriteSpeedY = 1
self.InitializeComponent()

def InitializeComponent(self):
self.graphics = GraphicsDeviceManager(self)
self.content = ContentManager(self.Services)

def LoadGraphicsContent(self, loadAllContent):
if loadAllContent:
self.texture = Texture2D.FromFile(self.graphics.GraphicsDevice, "sprite.jpg")
self.spriteBatch = SpriteBatch(self.graphics.GraphicsDevice)

def UnloadGraphicsContent(self, unloadAllContent):
if unloadAllContent:
self.texture.Dispose()
self.spritebatch.Dispose()

def Update(self, gameTime):
self.UpdateSprite()

Game.Update(self, gameTime)

def UpdateSprite(self):
self.spriteX += self.spriteSpeedX
self.spriteY += self.spriteSpeedY

maxX = self.graphics.GraphicsDevice.Viewport.Width - self.texture.Width
if self.spriteX > maxX:
self.spriteSpeedX *= -1
self.spriteX = maxX
elif self.spriteX < 0:
self.spriteSpeedX *= -1
self.spriteX = 0

maxY = self.graphics.GraphicsDevice.Viewport.Height - self.texture.Height
if self.spriteY > maxY:
self.spriteSpeedY *= -1
self.spriteX = maxY
elif self.spriteY < 0:
self.spriteSpeedY *= -1
self.spriteY = 0

def Draw(self, gameTime):
self.graphics.GraphicsDevice.Clear(Color.CornflowerBlue)

self.DrawSprite()

Game.Draw(self, gameTime)

def DrawSprite(self):
self.spriteBatch.Begin()
self.spriteBatch.Draw(self.texture, Rectangle(self.spriteX,
self.spriteY, self.texture.Width, self.texture.Height), Color.White)
self.spriteBatch.End()

game = MyGame()
game.Run()

Friday, March 30, 2007

Jython - SSH

Ganymed est une librairie java qui implémente le protocole SSH.
Et bien sûr on peut parfaitement l'utiliser sous Jython :-)
Voici un exemple de servlet Jython utlisant Ganymed.

http://www.ganymed.ethz.ch/ssh2/



from javax.servlet.http import HttpServlet
from ch.ethz.ssh2 import Connection,Session,StreamGobbler
from java.io import BufferedReader, InputStreamReader

hostname = '127.0.0.1'
username = 'admin'
password = 'Yu8KL%'

class MonServeur (HttpServlet):
def doGet(self,request,response):
self.doPost (request,response)
def doPost(self,request,response):
sortie = []
conn = Connection(hostname)
conn.connect()
isConnected = conn.authenticateWithPassword(username, password);
sess = conn.openSession()
sess.execCommand("uname -a && df -k")
stdout = StreamGobbler(sess.getStdout())
inputStreamReader = InputStreamReader(stdout)
br = BufferedReader(inputStreamReader)
toClient = response.getWriter()
response.setContentType ("text/html")
while (1):
line = br.readLine()
if line == None:
break
sortie.append(line)
toClient.println (sortie)

Wednesday, March 21, 2007

Utiliser Jython développer en Java

Jython est l'implémentation en Java du langage de programmation Python.
Il permet d'avoir accés à toutes les classes Java. En outre on peut très facilement
créer des applets, servlets, beans avec toute la simplicité du langage Python: le rêve.

Si vous voulez tester voici un lien qui explique comment par exemple
déployer une servlet Jython sur Tomcat. (J'ai testé cela marche très bien).

http://linuxgazette.net/issue97/tougher.html

Jython inclue la servlet "Pyservlet" qui permet de modifier la servlet et de l'exécuter sans recompilation !!!

Sunday, February 18, 2007

Saturday, February 17, 2007

Modules musicaux

Je viens de rajouter quelques morceaux de musique. Ne vous arrêtez aux premières mesures :-)
Malheureusement, la conversion au format mp3 réduit de façon notable la qualité du son et des effets. Mais bon c'est le prix à payer.
Si vous désirez en savoir un peu plus sur l'origine de ces oeuvres musicales, je vous conseille de visiter ce site : http://www.modarchive.org.

Bonne écoute...

Thursday, February 8, 2007

Impressionnant...

C'est le premier mot qui m'est venu à l'esprit en regardant le travail effectué par Jean-Michel Doudoux.
Voici un site qui ravira tous les utilisateurs du langage Java.
A lire absolument.
http://www.jmdoudoux.fr/java/dej/indexavecframes.htm

Sunday, February 4, 2007

Musique en ligne

La diffusion de musique en ligne peut-être réalisée très facilement, comme le témoigne ce site.
Pour ce qui est des fichiers mp3, il existe de nombreux sites sur l'internet qui pemettent de les stocker en ligne, et de les rendre disponible à travers des liens URL.
Personnellement j'utilise : http://www.snapdrive.net

Saturday, February 3, 2007

Inauguration

Google, met à disposition un certain nombre d'outils en ligne qui méritent véritablement le détour.
Pour quiconque n'a pas besoin d'un site sophistiqué, ces outils sont amplement suffisants, avec le gros avantage de ne plus avoir à s'occuper du stockage et de la disponibilité
J'ai décidé de franchir le pas.