[python-win32] A little help for a n00b, please

Tim Golden mail at timgolden.me.uk
Sun May 6 10:50:50 CEST 2012


On 06/05/2012 02:24, Alan Jump wrote:
> Trying to massage an older package (not written by me) into functioning
> order. The issue I'm having is getting printing functionality to work.
> The code snippet in question:
>
>          if platform.system() == 'Windows':
>              try:
>                  import win32api
>              except:
>                  print('* FAILED TO LOAD WINDOWS EXTENSION')
>                  return
>              try:
>                  win32api.ShellExecute (0, "print", filename, None, ".", 0)
>              except:
>                  print('* FAILED TO SEND PRINT TO WINDOWS PRINTER')
>                  return
>
> The output file is generated in a separate code section and the filename
> being passed has been verified, but I invariably get the message in the
> second exception. That tells me the win32api is being properly imported,
> but for some reason, it's throwing an exception when trying to write to
> the print device.

Some general advice for a start: you almost *never* want to
use a general except: clause (ie without a specific exception
class): it catches *everything* - including Ctrl-C. So, in
the try-except around "import win32api" you just want to
catch ImportErrors -- at least, I assume so.

However, you've circumvented that particular issue by removing
the except clause from your ShellExecute command. Contrary to
Vernon's suggestion, that won't actually be using the DOS
"print" command but rather passing the "print" verb along to
the application which is registered against the filename in
question via the Shell verb handling mechanism.

It would be interesting to see the exact error message you
get but permissions or UAC is definitely a possibility. Also,
and this is where it gets messier, the "print" verb will, in
most cases, go to the *default* printer on the machine you're
on -- and with the default settings. It's possible that this
isn't the printer you think it is. Some applications keep their
own track of which printer you last used, so you might fail to
realise which one is actually the default.

If that is the case you might want to look at this:

   http://timgolden.me.uk/python/win32_how_do_i/print.html#shellexecute

for a possible way to specify a printer.


TJG


More information about the python-win32 mailing list