| CodeWindows |
UserPreferences |
| Wiki Python Fr | FrontPage | RecentChanges | TitleIndex | WordIndex | SiteNavigation | HelpContents | moin.sf.net |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #! python
try:
import win32print
except:
print 'This script requires the win32print module (included in win32all).'
print 'See http://starship.python.net/crew/mhammond/win32/Downloads.html'
else:
try:
print 'List of local printers:'
for (Flags,pDescription,pName,pComment) in list(win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL,None,1)):
print ' ',pName
except:
print 'Could not get local printers list.'
try:
print 'List Network printers:'
for (Flags,pDescription,pName,pComment) in list(win32print.EnumPrinters(win32print.PRINTER_ENUM_CONNECTIONS,None,1)):
print ' ',pName
except:
print 'Could not get network printers list.' |
1 2 3 4 5 6 7 | #! python import _winreg key = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders',0, _winreg.KEY_READ) (valeur,typevaleur) = _winreg.QueryValueEx(key,'Fonts') _winreg.CloseKey(key) print valeur print typevaleur |
typevaleur est le type de la valeur (_winreg.REG_SZ, REG_BINARY, REG_DWORD... voir
http://docs.python.org/lib/module--winreg.html)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #! python
import _winreg
key = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders',0, _winreg.KEY_READ)
i = 0
try:
while True:
tp = _winreg.EnumValue(key,i) # mmm..strange, Should unpack to 3 values, but seems to unpack to more. Bug of EnumValue() ?
valuename = tp[0]
valuedata = tp[1]
valuetype = tp[2]
print 'La clé %s vaut "%s"' % (valuename,str(valuedata))
i = i+1
except EnvironmentError:
pass
_winreg.CloseKey(key) |
1 2 3 4 5 | #! python # La ligne suivante ouvre une clé et la créé si elle n'existe pas. key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, 'Software\\wikipython.flibuste.net\\monprogramme') _winreg.SetValueEx(key, 'nom_de_valeur',0, _winreg.REG_SZ, 'coucou !') _winreg.CloseKey(key) |
Nous avons créé une clé de type REG_SZ (chaîne de caractères).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #! python
import time
from win32com.client.gencache import EnsureDispatch
from win32com.client import constants
class InternetExplorerGetter:
def __init__(self):
self.ie = EnsureDispatch('InternetExplorer.Application')
def get(self, url):
self.ie.Navigate(url)
return self.waitForResult()
def refresh(self):
self.ie.Refresh()
return self.waitForResult()
def waitForResult(self):
while 1:
state = self.ie.ReadyState
if state == constants.READYSTATE_COMPLETE: break
time.sleep(0.1)
return self.ie.Document.documentElement.innerHTML
if __name__ == '__main__':
print InternetExplorerGetter().get('http://www.python.org') |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #! python
import win32com.client
excel = win32com.client.Dispatch('Excel.Application')
excel.Visible = 1
excel.Workbooks.Add()
line = ['one','two','three','four','five','six','seven','height','nine','ten']
column = ['','x','x^2','x^3','x^4']
for i in range(len(column)):
excel.ActiveSheet.Cells(i+1).Value = column[i]
# Ajoute de donnees dans les celulles
for i in range (len(line)):
j = i+2
excel.ActiveSheet.Cells(j,1).Value = line[i]
excel.ActiveSheet.Cells(j,2).Value = i
excel.ActiveSheet.Cells(j,3).Value = "=B%d+B%d" % (j,j)
excel.ActiveSheet.Cells(j,4).Value = "=B%d+B%d+B%d" % (j,j,j)
excel.ActiveSheet.Cells(j,5).Value = "=B%d+B%d+B%d+B%d" % (j,j,j,j)
# Selection des cellules
excel.Range("A1:D9").Select()
# Ajoute un graphique
excel.Charts.Add()
# Cree un camenbert
xlLineMarkers = 65
xlPieExploded = 69
excel.ActiveChart.ChartType = xlLineMarkers
# Cree un titre
excel.ActiveChart.HasTitle = 1
excel.ActiveChart.ChartTitle.Characters.Text = "MonTitre" |
Cette exemple ouvre un fichier et affiche son contenu:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #! python
import win32com.client
excel = win32com.client.Dispatch('Excel.Application')
classeur = excel.Workbooks.Open("H:/Documents and Settings/Julien/Bureau/fact/JANVIER 2005.xls")
feuille = classeur.ActiveSheet #On recupere la feuille courante
maxcol = feuille.UsedRange.Columns.Count #Recupere le nombre de colonne maximum
maxline = feuille.UsedRange.Rows.Count #Recupere le nombre de ligne maximum
for x in range(1, maxline):
for y in range(1, maxcol):
print feuille.Cells(x, y).Value #Affiche le contenu de la cellule x,y
#Pour récupérer un tableau de valeur, plus rapide que la double boucle for ci-dessus
#sht = classeur.Worksheets(feuille.name)
#rows= sht.Range(sht.Cells(1, 1), sht.Cells(maxline, maxcol)).Value
excel.Workbooks.Close()
excel.Quit() |
1 2 3 4 5 6 7 8 9 10 11 | #! python
import win32com.client
word = win32com.client.Dispatch("Word.Application")
word.Documents.Open("D:/partage/python/wordtxt/test.doc") #il faut mettre le chemin complet
text = word.ActiveDocument.content.text
word.Documents.Close()
text = text.encode('Latin-1')
print text |
L'adresse, c'est là : http://mclaveau.com/ress/python/pxword.htm
Vous trouverez également d'autres exemple d'utilisation de COM/DCOM dans CodesBDD (Manipulation de SQL Server et ADO).
Le module ctypes permet de faire des appels aux API Win32. Ce module est disponible à http://starship.python.net/crew/theller/ctypes/
1 2 3 4 | #! python import ctypes SPI_SETDESKWALLPAPER = 20 ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, "c:\\monrepertoire\\monpapierpeint.bmp" , 0) |
1 2 3 4 5 6 7 | #! python import ctypes SM_CXSCREEN = 0 SM_CYSCREEN = 1 taille_x = ctypes.windll.user32.GetSystemMetrics(SM_CXSCREEN) taille_y = ctypes.windll.user32.GetSystemMetrics(SM_CYSCREEN) print "La résolution d'écran est %d par %d" % (taille_x, taille_y) |
Un mutex est utile, par exemple, pour vérifier qu'une application est déjà lancée. Certain installeurs comme InnoSetup s'en servent également pour vérifier que l'application à déinstaller n'est pas en cours de fonctionnement.
Voici comment créer un mutex sous Windows. Cela nécessite le module ctypes.
1 2 3 4 5 6 7 8 9 10 11 12 13 | #! python
CTYPES_AVAILABLE = True
try:
import ctypes
except ImportError:
CTYPES_AVAILABLE = False
MY_MUTEX = None
if CTYPES_AVAILABLE and sys.platform=="win32":
try:
MY_MUTEX=ctypes.windll.kernel32.CreateMutexA(None,False,"mydomain_myprogramname")
except:
pass |
AutoIt est un langage de script qui permet d'automatiser plein de choses dans Windows (clic de boutons, entrée de texte, lancement de programmes, attente de fenêtres...). Il serait possible de faire la même chose en Python en manipulant l'API Win32, mais ce serait pénible. Il est bien plus facile d'utiliser directement AutoIt à partir de Python.
Exemple: lancer le bloc-note et taper un peu de texte dedans:
1 2 3 4 5 6 7 8 | #! python
import win32com.client
autoit = win32com.client.Dispatch("AutoItX3.Control")
autoit.Run("notepad.exe")
autoit.AutoItSetOption("WinTitleMatchMode", 4)
autoit.WinWait("classname=Notepad")
autoit.Send("Hello, world.") |
Voici quelques fonctions utiles pour administrer un serveur (surveillance de la taille de répertoires par exemple). Je m'en sert pour envoyer un mail demandant à ceux qui ont une corbeille de plus de 100 Mo de la vider.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | #! python
"""
Tailles des fichiers/répertoires dans windows
sous cmd, on peut faire par exemple :
dir /a:h /q /n/c/p e:\recycler
"""
import os
from win32com.client import Dispatch
import win32security
def getFileProprietary(fichier):
o = win32security.GetFileSecurity(fichier, win32security.OWNER_SECURITY_INFORMATION)
oo = o.GetSecurityDescriptorOwner()
nom, domaine, rien = win32security.LookupAccountSid('', oo)
return nom
def getFileSize(fichier):
return os.stat(fichier).st_size
def getDirectorySize(repertoire):
fso = Dispatch("Scripting.FileSystemObject")
return fso.GetFolder(repertoire).size
def tailleRepertoires(repertoire, proprietaire=False):
"""Renvoie une liste de (repertoire, taille, proprietaire)
taille est en kilo-octets."""
data = []
os.chdir(repertoire)
for rep in [r for r in os.listdir('.') if os.path.isdir(r)]:
rep = os.path.normpath(rep)
try:
taille = getDirectorySize(rep)
if proprietaire is True:
nom = getFileProprietary(rep)
except Exception, erreur:
taille = 0
nom = '-'
if proprietaire is True:
repertoire = (rep, taille/1024, nom)
else:
repertoire = (rep, taille/1024)
data.append( repertoire )
return data
#-------------------------------------------------------------------------------
if __name__ == '__main__':
poubelles = tailleRepertoires(r'c:\recycler', proprietaire=True)
poubelles.sort()
for rep, taille, nom in poubelles:
print '%7d' % taille, nomimport win32com.client |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #! python
import os
from win32netcon import RESOURCETYPE_DISK
import win32wnet
def lecteur_disponible():
for lettre in ('g:','h:','i:','j:','k:','l:','m:','n:','o:','p:','q:','r:',
's:','t:','u:','v:','w:','x:','y:','z:'):
lettre_path = lettre + '\\'
if not os.path.isdir(lettre_path):
return lettre
return None
class LecteurReseau:
"""Monter/Démonter un lecteur réseau."""
def __init__(self, chemin, utilisateur, mot_de_passe, lettre=None):
if lettre is None:
lettre = lecteur_disponible()
self.lettre = lettre
self.chemin = chemin
self.utilisateur = utilisateur
self.mot_de_passe = mot_de_passe
def monter(self):
win32wnet.WNetAddConnection2(RESOURCETYPE_DISK, self.lettre,
self.chemin, None, self.mot_de_passe, self.utilisateur)
return self.lettre
def demonter(self):
win32wnet.WNetCancelConnection2(self.lettre, 0, 0)
if __name__ == '__main__':
print 'Premier lecteur disponible : ', lecteur_disponible() |