What can you do with COM/ActiveX in Python? [closed]

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-27 06:30:20
luc

First you have to install the wonderful pywin32 module.

It provides COM support. You need to run the makepy utility. It is located at C:\...\Python26\Lib\site-packages\win32com\client. On Vista, it must be ran with admin rights.

This utility will show all available COM objects. You can find yours and it will generate a python wrapper for this object.

The wrapper is a python module generated in the C:\...\Python26\Lib\site-packages\win32com\gen_py folder. The module contains the interface of the COM objects. The name of the file is the COM unique id. If you have many files, it is sometimes difficult to find the right one.

After that you just have to call the right interface. It is magical :)

A short example with excel

import win32com.client

xlApp = win32com.client.Dispatch("Excel.Application")
xlApp.Visible=1

workBook = xlApp.Workbooks.Open(r"C:\MyTest.xls")
print str(workBook.ActiveSheet.Cells(i,1))
workBook.ActiveSheet.Cells(1, 1).Value = "hello"                
workBook.Close(SaveChanges=0) 
xlApp.Quit()

You can basically do the equivalent of late binding. So whatever is exposed through IDispatch is able to be consumed.

Here's some code I wrote this weekend to get an image from a twain device via Windows Image Acquisition 2.0 and put the data into something I can shove in a gtk based UI.

WIA_COM = "WIA.CommonDialog"
WIA_DEVICE_UNSPECIFIED = 0
WIA_INTENT_UNSPECIFIED = 0
WIA_BIAS_MIN_SIZE = 65536
WIA_IMG_FORMAT_PNG = "{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}"

def acquire_image_wia():
    wia = win32com.client.Dispatch(WIA_COM)
    img = wia.ShowAcquireImage(WIA_DEVICE_UNSPECIFIED,
                           WIA_INTENT_UNSPECIFIED,
                           WIA_BIAS_MIN_SIZE,
                           WIA_IMG_FORMAT_PNG,
                           False,
                           True)
    fname = str(time.time())
    img.SaveFile(fname)
    buff = gtk.gdk.pixbuf_new_from_file(fname)
    os.remove(fname)

return buff

It's not pretty but it works. I would assert it's equivalent to what you would have to write in VB.

Here is a working solution that creates a file and adds value to a cell:

import win32com.client
import xlsxwriter
import os
cwd = os.getcwd()
file_path = cwd + "\\test.xlsx"

#Create an excel file
workbook = xlsxwriter.Workbook(file_path)
worksheet = workbook.add_worksheet()
workbook.close()

#Open an excel application
xlApp = win32com.client.Dispatch("Excel.Application")
xlApp.Visible=1


workBook = xlApp.Workbooks.Open(file_path)
print str(workBook.ActiveSheet.Cells(1,1))
workBook.ActiveSheet.Cells(1, 1).Value = "hello55"                
workBook.Close(SaveChanges=1) 
xlApp.Quit()

How to receive ActiveX events in python 3

# coding=utf8

from PyQt5.QAxContainer import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QObject
import sys

TITLE = "CallX Python Example: accept any calls"
TrueConfCallX_Class = '{27EF4BA2-4500-4839-B88A-F2F4744FE56A}'

SERVER = '' # empty - connect to TrueConf Online cloud
USER = '<trueconf id>'
PASSWORD = '<password>'

class CallXWindow(QWidget):

    def __init__(self):
        QAxWidget.__init__(self)
        self.setWindowTitle(TITLE)
        self.move(400, 30)
# end of class CallXWindow(QWidget)


class ActiveXExtend(QObject):

    def __init__(self, view):
        super().__init__()
        self.view = view
        self.ocx = QAxWidget(TrueConfCallX_Class)

        self.ocx.move(0, 0)
        self.ocx.setFixedSize(640, 375)
        self.ocx.setParent(self.view)
        self.ocx.show()

        # receive some ActiveX events 
        self.ocx.OnXAfterStart.connect(self._OnXAfterStart)
        self.ocx.OnServerConnected[str].connect(self._OnServerConnected)
        self.ocx.OnLogin[str].connect(self._OnLogin)
        self.ocx.OnInviteReceived[str].connect(self._OnInviteReceived)
        self.ocx.OnXError[int, str].connect(self._OnXError)
        self.ocx.OnXLoginError[int].connect(self._OnXLoginError)

    # Events
    def _OnXAfterStart(self):
        print("**OnXAfterStart")
        # select devices
        self.ocx.XSetCameraByIndex(0)
        self.ocx.XSelectMicByIndex(0)
        self.ocx.XSelectSpeakerByIndex(0)
        # connect to server
        self.ocx.connectToServer(SERVER)

    def _OnServerConnected(self, eventDetails):
        print("**OnServerConnected")
        print(eventDetails)
        # login
        self.ocx.login(USER, PASSWORD)

    def _OnLogin(self, eventDetails):
        print("**OnLogin")

    def _OnInviteReceived(self, eventDetails):
        print("**OnInviteReceived")
        print(eventDetails)
        # accept any calls
        self.ocx.accept()

    def _OnXError(self, errorCode, errorMsg):
        print("**OnXError")
        print('{}. Code: {}'.format(errorMsg, errorCode))

    def _OnXLoginError(self, errorCode):
        print("**OnXLoginError")
        if errorCode == 8:
            print('Support for SDK Applications is not enabled on this server')
        else:
            print('Login error. Code: {}'.format(errorCode))
# end of class ActiveXExtend(QObject)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    MainWindow = CallXWindow()
    axwin = ActiveXExtend(MainWindow)
    MainWindow.show()
sys.exit(app.exec_())
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!