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)

Send email with Outlook and Python

A simple example to send emails via Outlook and Python win32com.

import win32com.client

s = win32com.client.Dispatch("Mapi.Session")
o = win32com.client.Dispatch("Outlook.Application")
s.Logon("Outlook2003")
    
Msg = o.CreateItem(0)
Msg.To = "recipient@domain.com"
    
Msg.CC = "more email addresses here"
Msg.BCC = "more email addresses here"
    
Msg.Subject = "The subject of you mail"
Msg.Body = "The main body text of you mail"
    
attachment1 = "Path to attachment no. 1"
attachment2 = "Path to attachment no. 2"
Msg.Attachments.Add(attachment1)
Msg.Attachments.Add(attachment2)
 
Msg.Send()

Read from Microsoft Access via DAO and Python

Simple Database access to Microsoft Access via DAO and Python on Windows.

import win32com.client
daoEngine = win32com.client.Dispatch('DAO.DBEngine.35')
db = 'c:\\test\\mydatabase.mdb'
daoDB = daoEngine.OpenDatabase(db)
query = 'SELECT * FROM my_table WHERE my_attribute = 'my_search_value'
daoRS = daoDB.OpenRecordset(query)
print daoRS
daoRS.Close()

Copy big files on Windows

A short Python script (from Activestate) to copy very big files on Windows:

import win32file

def copy_big_file(srcname, dstname):
        hin= win32file.CreateFile(
                srcname,
                win32file.GENERIC_READ,
                0, # win32file.FILE_SHARE_READ,
                None,
                win32file.OPEN_EXISTING,
                win32file.FILE_FLAG_SEQUENTIAL_SCAN,
                0)
##        print "type of hin=%r" % type(hin)
        hou= win32file.CreateFile(
                dstname,
                win32file.GENERIC_WRITE,
                0, # win32file.FILE_SHARE_READ,
                None,
                win32file.CREATE_ALWAYS,
                win32file.FILE_FLAG_SEQUENTIAL_SCAN,
                0)
        while 1:
                rc, buffer= win32file.ReadFile(hin, 65536)
                if not buffer: break
                if rc == 0:
                        win32file.WriteFile(hou, buffer)
                else:
                        print "rc=%d" % rc
                        break
        hin.Close()
        hou.Close()

Find all Windows Shell Folder (Special Folder) Locations

Quick method to find the location of the current user’s special folders and return them in a dictionary keyed on the folder name.

Two ways below to enum all the shell folder registry keys. The for loop version shown is safer. The while components are there but commented out, just note that it relies on an exception error to indicate the end of the key has been reached, so there is a small chance that some unknown condition could cause it to never terminate, so the for loop is safer.

user_dict = Get_User_ShellFolders()
print user_dict

def Get_User_ShellFolders():
    # Routine to grab all the Windows Shell Folder locations from the registry.  If successful, returns dictionary
    # of shell folder locations indexed on Windows keyword for each; otherwise, returns an empty dictionary.
    import _winreg
    return_dict = {}

    # First open the registry hive
    try:
        Hive = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER)
    except WindowsError:
        print "Can't connect to registry hive HKEY_CURRENT_USER."
        return return_dict

    # Then open the registry key where Windows stores the Shell Folder locations
    try:
        Key = _winreg.OpenKey(Hive, "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
    except WindowsError:
        print "Can't open registry key Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders."
        _winreg.CloseKey(Hive)
        return return_dict

    # Nothing failed above, so enumerate through all the Shell Folder values and return in a dictionary
    # This relies on error at end of 
    try:
        #i = 0
        #while 1:
        for i in range(0, _winreg.QueryInfoKey(Key)[1]):
            name, value, val_type = _winreg.EnumValue(Key, i)
            return_dict[name] = value
            i += 1
        _winreg.CloseKey(Key)                           # Only use with for loop
        _winreg.CloseKey(Hive)                          # Only use with for loop
        return return_dict                              # Only use with for loop
    except WindowsError:
        # In case of failure before read completed, don't return partial results
        _winreg.CloseKey(Key)
        _winreg.CloseKey(Hive)
        return {}

Example Output:

{
        'Templates': u'C:\\Documents and Settings\\username\\Templates', 
        'Cookies': u'C:\\Documents and Settings\\username\\Cookies', 
        'Fonts': u'C:\\WINNT\\Fonts', 
        'PrintHood': u'C:\\Documents and Settings\\username\\PrintHood', 
        'AppData': u'C:\\Documents and Settings\\username\\Application Data', 
        'Programs': u'C:\\Documents and Settings\\username\\Start Menu\\Programs', 
        'Personal': u'C:\\Documents and Settings\\username\\My Documents', 
        'Local Settings': u'C:\\Documents and Settings\\username\\Local Settings', 
        'Cache': u'C:\\Documents and Settings\\username\\Local Settings\\Temporary Internet Files', 
        'Startup': u'C:\\Documents and Settings\\username\\Start Menu\\Programs\\Startup', 
        'Desktop': u'C:\\Documents and Settings\\username\\Desktop', 
        'Start Menu': u'C:\\Documents and Settings\\username\\Start Menu', 
        'NetHood': u'C:\\Documents and Settings\\username\\NetHood', 
        'Local AppData': u'C:\\Documents and Settings\\username\\Local Settings\\Application Data', 
        'Favorites': u'C:\\Documents and Settings\\username\\Favorites', 
        'SendTo': u'C:\\Documents and Settings\\username\\SendTo', 
        'History': u'C:\\Documents and Settings\\username\\Local Settings\\History', 
        'My Pictures': u'C:\\Documents and Settings\\username\\My Documents\\My Pictures', 
        'Recent': u'C:\\Documents and Settings\\username\\Recent'
}

Get List of IP Routes

Quick method to extract the IP routing table on a PC into a list of lists using a single list comprehension.

Each route table entry is stored in a list where:

[0] = Network Destination
[1] = Netmask
[2] = Gateway
[3] = Interface
[4] = Metric

The active default route will always be the first list in the results [0], so the default next hop for unknown destinations will be [0][3].

from os import popen
from string import split, join
from re import match

rtr_table = [elem.strip().split() for elem in popen("route print").read().split("Metric\n")[1].split("\n") if match("^[0-9]", elem.strip())]

print "Active default route:", rtr_table[0]

print "Active default next hop:", rtr_table[0][3]

The above comprehension relies on the “Metric” header value. I later realized this may not scale to non-U.S. PCs so here’s a different comprehension that should work for all regions.

[elem.strip().split() for elem in popen("route print").read().split("\n") if match("^[0-9]", elem.strip()) and is_IPv4_Addr(elem.strip().split()[0])]

Important: The above comprehensions don’t take into account that “route print” may be invalid on some PCs…though I’ve never seen this in practice. So you may want to capture the popen output first and check to make sure it’s not blank so the comprehension doesn’t throw an exception.

    return_vals = popen("route print").read()
    if return_vals:
        # U.S. Version
        #rtr_table = [elem.strip().split() for elem in return_vals.split("Metric\n")[1].split("\n") if match("^[0-9]", elem.strip())]

        # Universal Version ?
        return [elem.strip().split() for elem in return_vals.split("\n") if match("^[0-9]", elem.strip()) and is_IPv4_Addr(elem.strip().split()[0])]