Using a TLB-defined interface with Python and COM - python

I will try to keep this question as tight as possible, but if it seems that I am saying insane things, it is almost certainly because I am ignorant of some key point, so please do correct me.
I am writing a program, in a Windows environment, that will interface with an existing application that has a COM interface to allow 3rd-party software to interact with it.
I have read all of the documentation for this application, and it says that there is a TLB file that defines the functions and data available via COM.
How do I use the TLB file with python? How do I discover the progID of the application so that I can interface with it (this isn't given in the documentation).
I'm pretty lost. I have a fair amount of experience with Python, but I am completely new to developing in a Windows environment. Any help would be enormously helpful. I have been reading all the documentation on win32com, but I still have no clue what to do, as no one addresses -- as far as I have seen -- bringing in a TLB file.

The questions asked is to link the custom TLB file with COM client to be developed in python. I have done a small example code for my COM server developed in C# and same is accessed by python client using "comtypes" package.
The below snippet of code gives:
import comtypes.client as CC
import comtypes
ccHandle = CC.CreateObject("CSharpServer.InterfaceImplementation")
print (ccHandle)
import comtypes.gen.CSharpServer as CS
InterfaceHandle = ccHandle.QueryInterface(CS.IManagedInterface)
print ("output of PrintHi function = ", InterfaceHandle.PrintHi("World"))
The above python script is for the C# COM server code available at http://msdn.microsoft.com/en-us/library/aa645738(v=vs.71).aspx (refer to the File 1: CSharpServer.cs).

OK, it's been a while since I've done this, and I'm not a COM expert by any means. Read the COM chapter from Python Programming on Windows to see how to do this. Follow along with the examples (trying things out against Excel) to get a feel of how things work.
First off, install the PyWin32 Extensions if you haven't already. This is the package that gives you pythonwin.exe and the COM interface modules. Get it from here.
Then you are going to open the "COM Makepy Utility" from PythonWin's Tools menu. Browse through the list of registered COM components (some will be typelibs, others DLLs) until you identify the one you have (you have to do a bit of detective work). Click OK to generate the Python glue code. You will then need to run it again with the -i command-line argmument to generate the boilerplate code so your python script can use this glue. Here's a paraphrase of the O'Reilly example for the Microsoft Excel Object library:
import win32com.client
from win32com.client import gencache
gencache.EnsureModule('{00020813-0000-0000-C000-000000000046}', 0, 1, 2)
earlyBound = win32com.client.Dispatch("Excel.Application")
lateBound = win32com.client.dynamic.Dispatch("Excel.Application")
print earlyBound.ActiveCell()
Using early-bound objects is optional, but it does improve performance.
To find the ProgID is again a bit of detective work, although this answer seems to imply it's going to be hard. Try poking around the HKEY_CLASSES_ROOT hive of the registry with RegEdit to see if you see a ProgID that looks promising.

Related

Python in a webapp (client side)

This is part of some preliminary research and I am having a difficult time figuring out what options might be available or if this is even a situation where a solution even exists.
Essentially we have an existing python based simulation that we would like to make available to people via the web. It can be pretty processor intensive, so while we could just run the sim server side and write a client that connects to it, this would not be ideal.
Writing a UI in Flash/Flex or HTML5, not a problem. However, is there any way to keep the core simulation logic in python without having it live server side? Is there any existing way to embed python modules in either of these technologies?
Thanks all.
Pyjamas: Python->Javascript, set of widgets for use in a browser or a desktop
Skulpt: Python written in Javascript
Emscripten: C/C++ -> LLVM -> Javascript
Empythoned: Based on emscripten and cpython, working on a stdlib? There are bugs to file

readline help feature & autocomplete

im willing to create a project same as JUNOS cli or cisco cli,
I came through gnu readline, but im confused as there are too many functions and methods to implement. any how i want a cli with auto complete using tab and space bar with question mark to display commands with help text.
I have two questions :
I have found code in python and perl but the im not use to python that code is complete and i just want to know if i should continue with python. im more experienced in perl but the code i found so far isn't complete for perl.
readline.parse_and_bind('tab: complete')
should i use the same complete function for both help and autocomplete feature. where as i have gone through another function
readline.set_completion_display_matches_hook(print_suggestions)
what you suggest :P im completely new to it!
I must say that I struggle to understand which specific point you are addressing in your question. But here is a suggestion anyway:
Start out with the cmd module. It gives you a nice little framework to build a command-line interpreter. It supports tab completion out of the box (provided readline is available). Start implementing your command-line interface. Once this stabilizes you can think about adding more comfort, e.g. tab completion for command arguments, help keys, and the like. This way, you have a working app to deal with, and can address readline details more specifically when you really need them. I wouldn't wade through the whole readline API upfront, if I were in your shoes.
We had to create a cli like JunOS/Cisco/VyOS and we built it on top of ishell, which uses readline for this job.
From the project page:
ishell helps you to easily create an interactive shell for your application. It supports command completion, dynamic arguments, a command history, and chaining of commands.
You can check the project at github: https://github.com/italorossi/ishell
Cisco example:
PS: I'm the author :).

Scripting OpenOffice Forms with VB or python

I'm trying to script my OpenOffice document (Writer in my case) to do some simple things with widgets. Namely I'd like to copy text from widget to widget. For this I want to get one component and than get text from it.
I've been trying to do sth like this:
document = ThisComponent.CurrentController.Frame
oDocument = ThisComponent
oTextBoxFrom = document.getByName("Text Box 1") # 1
oTextBoxFrom = oDocument.getByName("Text Box 1") # 2
Neither version #1 nor #2 work. VB compiler spits out that "Text Box 1" is not accessible, however I have that component in my form. My guess is that I'm trying to get this component from a wrong place, eg. not it's frame. I just can't figure out what is the structure of the document.
This seems like a pretty easy task, however I'm unable to find any OpenOffice specification as for accessing OO UNO objects from VB, or python.
Good day.
if you choose use a VB, you must know this:
VBA : Compatibility between OpenOffice.org Basic and VBA relates to
the OpenOffice.org Basic language as well as the runtime library. The
OpenOffice.org API and the Dialog Editor are not compatible with VBA
(standardizing these interfaces would have made many of the concepts
provided in OpenOffice.org impossible).
if it will be python:
OpenOffice.org 3.1 ships with the Python scripting language, version
2.6.1. Older OpenOffice.org ships with Python version 2.3.4. This Python distribution comes with the Uno module, which connects the UNO
API to the python scripting language. To run this version of Python on
Linux, you can go directly to the OpenOffice.org PATH. And as one
would expect with any distribution of Python, OOo-Python can be run
from the command line as well. If you already have a separate Python
2.6 installation, you can import the uno module (the Python-UNO bridge) to it using these instructions. If you already have a
different version of Python installed on Windows, you can also access
the UNO API using the COM bridge instead of the Python bridge.
Requires the add-on pywin32 module so Python can talk to COM. Note
that while the UNO API is uniform, the implementation by the two
bridges is slightly different, so the syntax required by each is also
sometimes different.
Python UNO bridge
upd: ooobloger might help you with understanding of python and uno integration.
i don't have experience with openoffice scripting but i found thes examples, note they never use getByName on the document itself but always on some part of it.
docCalc = ThisComponent
maFeuille = docCalc.Sheets.getByName("leCSV")
....
for f = 0 to lesFamilles.Count -1' chaque famille
nomFam = lesFamilles.ElementNames(f)
uneFamille = lesFamilles.getByName(nomFam)
...
monDocument.TextTables.hasByName("Finances")
...
lesSections = monDocument.TextSections
sectA = lesSections.getByName("Aline")
you can find the rest in this large pdf at http://oqei.free.fr/echange/VBA/Programmation_OpenOffice_org_3_ed1_v1.pdf ,it's in french but code is universal eh ?
Hope it helps..

Is there a cross-platform python low-level API to capture or generate keyboard events?

I am trying to write a cross-platform python program that would run in the background, monitor all keyboard events and when it sees some specific shortcuts, it generates one or more keyboard events of its own. For example, this could be handy to have Ctrl-# mapped to "my.email#address", so that every time some program asks me for my email address I just need to type Ctrl-#.
I know such programs already exist, and I am reinventing the wheel... but my goal is just to learn more about low-level keyboard APIs. Moreover, the answer to this question might be useful to other programmers, for example if they want to startup an SSH connection which requires a password, without using pexpect.
Thanks for your help.
Note: there is a similar question but it is limited to the Windows platform, and does not require python. I am looking for a cross-platform python api. There are also other questions related to keyboard events, but apparently they are not interested in system-wide keyboard events, just application-specific keyboard shortcuts.
Edit: I should probably add a disclaimer here: I do not want to write a keylogger. If I needed a keylogger, I could download one off the web a anyway. ;-)
There is no such API. My solution was to write a helper module which would use a different helper depending on the value of os.name.
On Windows, use the Win32 extensions.
On Linux, things are a bit more complex since real OSes protect their users against keyloggers[*]. So here, you will need a root process which watches one of[] the handles in /dev/input/. Your best bet is probably looking for an entry below /dev/input/by-path/ which contains the strings "kbd" or "keyboard". That should work in most cases.
[*]: Jeez, not even my virus/trojan scanner will complain when I start a Python program which hooks into the keyboard events...
As the guy that wrote the original pykeylogger linux port, I can say there isn't really a cross platform one. Essentially I rewrote the pyhook API for keyboard events to capture from the xserver itself, using the record extension. Of course, this assumes the record extension is there, loaded into the x server.
From there, it's essentially just detecting if you're on windows, or linux, and then loading the correct module for the OS. Everything else should be identical.
Take a look at the pykeylogger source, in pyxhook.py for the class and implimentation. Otherwise, just load that module, or pyhook instead, depending on OS.
I've made a few tests on Ubuntu 9.10. pykeylogger doesn't seems to be working. I've tryied to change the /etc/X11/xorg.conf in order to allow module to be loaded but in that specific version of ubuntu there is no xorg.conf. So, in my opiniion pykelogger is NOT working on ubuntu 9.10 !!
Cross-platform UI libraries such as Tkinter or wxPython have API for keyboard events. Using these you could map «CTRL» + «#» to an action.
On linux, you might want to have a look at pykeylogger. For some strange reason, reading from /dev/input/.... doesn't always work when X is running. For example it doesn't work on ubuntu 8.10. Pykeylogger uses xlib, which works exactly when the other way doesn't. I'm still looking into this, so if you find a simpler way of doing this, please tell me.
Under Linux it's possible to do this quite easily with Xlib. See this page for details:
http://www.larsen-b.com/Article/184.html

scripting fruityloops or propellerheads reason from VB or Python?

I have both Fruityloops and Propellerheads Reason software synths on my Windows PC.
Any way I can get at and script these from either Visual Basic or Python? Or at least send Midi messages to the synths from code?
Update : attempts to use something like a "midi-mapper" (thanks for link MusiGenesis) don't seem to work. I don't think Reason or FL Studio act like standard GM Midi synths.
Update 2 : If you're interested in this question, check out this too.
Both applications support MIDI. It's just that they don't see each other.
In order to send messages via MIDI between applications, you need to install a virtual midi port.
There are several freely available, but this one works: http://www.midiox.com/zip/MidiYokeSetup.msi
You'll get a virtual MIDI output port that you can write to as if it's a normal MIDI device. In Fruity Loops or Rebirth you choose that port as the input. That's all you need to do to connect the programs.
It'll work like this:
Your Application --> Virtual MIDI Port --> FruityLoops
Note: This answer doesn't exactly answer the question you asked but it might achieve the result you want :)
You can author a VST plugin in Java using jVSTWrapper (http://jvstwrapper.sourceforge.net/). If you really wanted to use Python you could use Jython to interface to java and do it that way. Alternatively you could just write the plugin in Java or another scripting language for the JVM like Groovy.
I think both FL Studio and Reason can be configured as the default MIDI playback device. To send MIDI messages to either from VB.NET, you'll need to PInvoke the midiOutOpen, midiOutShortMsg and midiOutClose API calls. Here's a link to code samples:
http://www.answers.com/topic/midioutopen
They're for VB6, but they should be easy to translate to VB.NET.
I know FL Studio can be "driven" from a plugin authored for FL (or a VSTx plugin), but I think these are always written in C or C++.
Edit: I just learned that Windows Vista dropped the MIDI Mapper (which would have made setting up FL or Reason as the default MIDI device simple). Amazing. Here is a link I found with an alternative solution:
http://akkordwechsel.de/15-windows-vista-und-der-midi-mapper/
I just tried it out (it's just a *.CPL file that you double-click to run) and it appears to work (although the GM Synth is the only option available on my laptop, so I'm not sure if it will pick up FL or Reason as choices).
What you need is a VST MIDI scripter / scripting plugin to create a logic of MIDI events that can be sent to any MIDI channel. You would need to set a MIDI channel in FL for the VST instrument/effect you need to tweak its values. Google for it there are some plugins around and please share them back here if you find anything useful :)
You could write a Rewire host. Though, you will have to get a license (the license is free, but your application must be proprietary, so no open source).
Alternatively, you could interface through MIDI messages.
Finally, you could implement a dummy audio device which would route the audio to/from wherever you want or process it in some way.
I imagine all of these would be reasonably difficult. MIDI is probably the easiest of the three (I have no idea how easy or hard the Rewire protocol is to use).
When it comes to Reason, you can do with it to much because of it's closed architecture - you can use VST plugins (or any other type like DirectX ones) - your only option is to use MIDI.
Regarding Fruity Loops, you could write a VST plugin that can take an input from a scripting language (VB, Python or whatever) but in order to write such thing you would have to use Delphi or C++.
Alternatively, you can check out MAX made by Cycling74 - it's something like a IDE for music ;-) - and I'm pretty sure you can use Python with it.
There's an opensource music workstation, called Frinika, and you can script that in Javascript. (Insert / delete notes , change midi effects like pitch wheel etc.) It can import / export regular midi files, so it will work with Fruity loops or whatever else you have.
// Insert New
song.newLane("MyMidiLane", type("Midi"));
lane = song.getLane("MyMidiLane");
part = lane.newPart( time("10.0:000"), time("4.0:000") );
part.insertNote(note("c#3"), time("11.2:000"), time("2:0"), 120 );
part.insertNote(note("f3"), time("11.3:000"), time("1:0"), 100 );
part.insertNote(note("g#3"), time("11.3:000"), time("1:0"), 100 );
part.insertNote(note("b3"), time("11.3:000"), time("0:64"), 100 );
part.removeNote(note("f3"), time("11.3:000"));
part = song.newLane("MyTextLane",
type("Text")).newPart(time("24.0:000"), time("10.0:000"));
part.text = "This is the test text to be inserted.";
part.lane.parts[0].remove(); // remove initially inserted text-part
Another example for reading/changing notes:
lane = song.getLane("MyMidiLane");
// a lane has a fixed instrument assigned
lane.parts[0].notes[0].duration=64
lane.parts[0].notes[1].duration=32
lane.parts[0].notes[1].startTick=120
// Parts are blocks of notes that you can drag around together in the Frinika GUI.
// They're like patterns in trackers.
for (i in lane.parts[0].notes){
println("i: "+i+", n: "+noteName(lane.parts[0].notes[i].note));
println("i: "+i+", dur: "+lane.parts[0].notes[i].duration);
println("i: "+i+", startT: "+lane.parts[0].notes[i].startTick);
}
http://frinika.appspot.com/
It has a Java Webstart launcher as well, so you don't even have to
install.
It used to bundle the Javadoc documentation as well, but for some
reason their latest downloads don't include that. It's a pity, because
that's where the Javascript bindings are documented. So, now you have
to browse the source or build the Javadoc yourself. (It has some built-in examples that are accessible from the scripting window, you should check them out first. My first example is from there.)
Here is the sourcefile where you'll find the Javascript docs:
frinika Javascript doc/source
But there are other options as well. You can check out mingus too, which is a Python library for music theory and midi file handling. It requires Fluidsynth, and the demo apps require GamePython too, so it's a bit more complicated to setup than Frinika.
P.S.:
Frinika has a particular bug: when dragging around neighbouring notes, some might not sound the right length. You can help that by transposing forth and back the consecutive notes (fairly fast in piano roll view), or dragging the part that contains the notes forth and back. Restarting Frinika will also help, but that's the slower way. So this bug won't affect saved files, neither midi export.

Categories

Resources