What is the equivalent of perl's Win32::OLE::Variant in Python 3

397 Views Asked by At

I have the following code snippet in perl for automating an application script using Win32::OLE

    use Win32::OLE;
    use Win32::OLE::Variant;
    my $app = new Win32::OLE 'Some.Application';
    my $InfoPacket = "78 00 C4 10 95 B4
                      00 02 31 7F 80 FF";
    my @Bytes = split(/[ \n][ \n]*/, $InfoPacket);
    my @HexBytes;
    foreach(@Bytes)
    {
        push @HexBytes, eval "0x$_";
    }
    my $Packet = pack("C12", @HexBytes);
    my $VarPacket = Variant(VT_UI1, $Packet);
    my $InfoObj = app -> ProcessPacket($VarPacket);
    print $InfoObj -> Text();

I have converted the entire code in Python 3, except for the [exact] equivalent of pack() and Variant() functions.

    from win32com.client import Dispatch
    from struct import pack
    app = Dispatch("Some.Application")
    InfoPacket = "78 00 C4 10 95 B4 \
                  00 02 31 7F 80 FF"
    Bytes = InfoPacket.split()
    HexBytes = [int(b, 16) for b in Bytes]
    Packet = pack('B'*12, *HexBytes)       # This however, is not giving the exact same output as perl's...
    VarPacket = ...                         # Need to know the python equivalent of above Variant() function...
    InfoObj = app.ProcessPacket(VarPacket)
    print (InfoObj.Text())

Please suggest the python equivalent of the pack() and Variant() functions used in perl script in the given context so that the final variable VarPacket can be used by Python's Dispatch object to properly generate the InfoObj object.

Thanks !!!

1

There are 1 best solutions below

1
Håkon Hægland On

I am not sure about the Python equivalent of the Perl Variant, but for the first question about packing the unsigned char array, the following works for me:

from struct import pack

def gen_list():
    info_packet = "78 00 C4 10 95 B4 00 02 31 7F 80 FF"
    count = 0
    for hex_str in info_packet.split():
        yield int(hex_str, 16)
        count += 1
    for j in range(count, 120):
        yield int(0)


packet = pack("120B", *list(gen_list()))

Edit

From the test file testPyComTest.py it looks like you can generate the variant like this:

import win32com.client
import pythoncom

variant = win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_UI1, packet)