Export variables on win32 like in Unix

This script comes from Activestate. It exports a variable permanently on win32 – without needing to reboot the system. Note: pywin32 must be installed to run the script.

Use it like this:

import win32export
win32export.export("fooname" , "foovalue")

And here comes the script. Save it as win32export.py and use it from other scripts or from the command line.

"""
vim: set enc=utf-8

Author :  winterTTr
Mail   :  winterTTr (at) gmail.com
Desc   :  Tools for Operation on Win32 Environment variables
Module :  win32export.py
"""

import win32gui
import win32con
import win32api

def export ( name , value , update_system = True ):
    try :
        modifyVariableInRegister( name , value )
    except:
        return False

    if update_system :
        updateSystem()

    return True

def modifyVariableInRegister( name , value ):
    key = win32api.RegOpenKey( win32con.HKEY_CURRENT_USER,"Environment",0,win32con.KEY_ALL_ACCESS)
    if not key : raise
    win32api.RegSetValueEx( key , name , 0 , win32con.REG_SZ , value )
    win32api.RegCloseKey( key )

def updateSystem():
    rc,dwReturnValue = win32gui.SendMessageTimeout( win32con.HWND_BROADCAST , win32con.WM_SETTINGCHANGE , 0 , "Environment" , win32con.SMTO_ABORTIFHUNG, 5000)

Adobe Photoshop automation

The following script adjusts the brightness and contrast of an image via COM automation of Adobe Photoshop with Python and the win32com package.

import win32com.client  
psApp = win32com.client.Dispatch("Photoshop.Application") 
psApp.Open(r"D:\temp\blah.psd")         # Opens a PSD file  
doc = psApp.Application.ActiveDocument  # Get active document object  
layer = doc.ArtLayers[0]                # Get the bottom-most layer  
layer.AdjustBrightnessContrast(20,-15)  # Bright +20, Contrast -15  
doc.Save() 

This comes from http://techarttiki.blogspot.com/2008/08/photoshop-scripting-with-python.html where you can find more excellent examples to automate Adobe Photoshop.

Alarm clock on a Windows machine

Following example comes from Activestate (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/510387) and represents an alarm clock on Windows:

try:
    import os
    import sys
    import time
    import msvcrt
    import winsound
except ImportError, error:
    sys.stdout.write('ImportError: %s' % error)
    sys.exit(1)

def main():
    try:
        arg = time.strptime(sys.argv[1], '%H:%M')
        arg_sec = (arg.tm_hour * 60 + arg.tm_min) * 60
        now = time.localtime()
        now_sec = (now.tm_hour * 60 + now.tm_min) * 60 + now.tm_sec
        alarm(arg_sec - now_sec + (86400 if arg_sec <= now_sec else 0))
    except:
        sys.stdout.write(os.path.basename(sys.argv[0]))
        sys.stdout.write(' HH:MM')

def alarm(seconds):
    time.sleep(seconds)
    while msvcrt.kbhit():
        msvcrt.getch()
    while not msvcrt.kbhit():
        winsound.Beep(440, 250)
        time.sleep(0.25)

if __name__ == '__main__':
    main()

Simple OpenOffice COM auomation example

from win32com.client.dynamic import Dispatch
objServiceManager = Dispatch('com.sun.star.ServiceManager')
Stardesktop = objServiceManager.CreateInstance('com.sun.star.frame.Desktop')
doc = Stardesktop.loadComponentfromURL('private:factory/swriter', '_blank', 0, [])
text = doc.getText()
text.setString("Hello World") 

Let merlin think (MS Agent automation)

import win32com.client
ag=win32com.client.Dispatch("Agent.Control")
ag.Connected=1
ag.Characters.Load("Merlin")
ag.Characters("Merlin").Show()
text = raw_input("please type something...")
ag.Characters("Merlin").Think(text)

Autocad Automation

This example comes from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440493. It searches the ModelSpace collection for text objects. Once found it casts them and alter one of the text specific properties. To test this code AutoCAD must be started with a blank file open add at least one dtext object with ‘Spam’ as its value:

import win32com.client
acad = win32com.client.Dispatch("AutoCAD.Application")

doc = acad.ActiveDocument   # Document object
ms = doc.ModelSpace         # Modelspace "collection"
count = ms.Count            # Number of items in modelspace

for i in range(count):
    item = ms.Item(i)
    if 'text' in item.ObjectName.lower(): # Text objects are AcDbText
        # once we know what it is we can cast it
        text = win32com.client.CastTo(item, "IAcadText") 
        if text.TextString == "Spam":
            text.TextString = "Maps"
            text.Update()

Outlook Web Access via Python

Adrian Holovaty wrote a small Python script to access Microsoft Outlook Web Access. It can do some actions by commandline via screen scraping. The script lets you access your emails (in raw format, with all headers) from the Microsoft Outlook’s webmail interface.

It works by screen-scraping the interface. Possible actions are:

  • Log into a Microsoft Outlook Web Access account with a given username and password
  • Retrieve all email IDs from the first page of Inbox
  • Retrieve full, raw source of the email with a given ID
  • Delete an email with a given ID (move to”Deleted Items” folder)

Download the script

Adobe Acrobat and Acrobat 3D Batch extension

This is a PDF Batch Converter extension for Adobe Acrobat and Acrobat 3D. This tool converts 3D CAD models to 3D-PDF as well as Office documents to PDF and works in following modes:

  • Convert single files
  • Convert files in a directory in batch
  • Converts a type of files with wildcards like *.CATPart, *.prt, *.model, …
  • Works as a deamon which watches into a directory (directory watcher)

If you want to download a compiled version: http://www.goermezer.de/dmdocuments/Acrobat2PDF.zip

If you want to use the source with a Python interpreter, it needs a config.ini with this content:

# Configuration of Acrobat2PDF:
[configsection]

# Only for usage as a server/deamon process
# Poll time is the time in seconds for each loop of conversion

polltime = 10

And here comes the Python source code. Pywin32 needed.

from __future__ import with_statement
"""
 Adobe Acrobat2PDF Batch Converter
 This tool converts all Office Documents to PDF and a lot of 3D CAD models
 to 3D-PDF
 Copyright Mustafa Goermezer
 http://www.goermezer.de
"""
import getopt
import os
from win32com.client.dynamic import Dispatch
import pythoncom
import win32gui
import time
import sys
import glob
import string
import ConfigParser
import datetime


def LoadConfig(file, config={}):
    """
    returns a dictionary with key's of the form
    
.

Convert a 3D model with SolidWorks to 3DXML

An example how to convert a SolidWorks part to 3DXML:

import win32com.client

app=win32com.client.Dispatch("SldWorks.Application")
doc=app.OpenDoc("c:\\Testpart.SLDPRT", 1)
doc.SaveAs2("c:\\Testpart.3dxml", 0, True, False)

Create Windows users

A simple script to create a user on Windows with Python

import win32netcon, win32net
d={}
d['name'] = "PythonTestUser"
d['password'] = "Top Secret"
d['comment'] = "A user created by some Python demo code"
d['flags'] = win32netcon.UF_NORMAL_ACCOUNT | win32netcon.UF_SCRIPT
d['priv'] = win32netcon.USER_PRIV_USER
win32net.NetUserAdd(None, 1, d)