5

我一直在寻找原始问题的答案。我如何确定(以编程方式)我的 win32api.ShellExecute 语句成功执行,如果成功执行,则执行 os.remove() 语句。

研究我发现 ShellExecute() 调用返回 HINSTANCE。进一步挖掘我发现 ShellExecute() 如果成功,将返回 HINSTANCE > 32。我现在的问题/问题是,我如何使用它来控制程序的其余部分?我尝试使用if HINSTANCE> 32:语句来控制下一部分,但我收到一条NameError: name 'hinstance' is not defined消息。通常这不会让我感到困惑,因为这意味着我需要在引用它之前定义变量“hinstance”;但是,因为我认为 ShellExecute 应该返回 HINSTANCE,所以我认为它可以使用?

这是我试图实现它的完整代码。请注意,在我的 print_file() def 中,我将 hinstance 分配给完整的 win32api.ShellExecute() 命令,以尝试捕获 hinstance 并在函数末尾显式返回它。这也不起作用。

import win32print
import win32api
from os.path import isfile, join
import glob
import os
import time

source_path = "c:\\temp\\source\\"

def main():
    printer_name = win32print.GetDefaultPrinter()
    while True:
        file_queue = [f for f in glob.glob("%s\\*.txt" % source_path) if isfile(f)]
        if len(file_queue) > 0:
            for i in file_queue:
                print_file(i, printer_name)
                if hinstance > 32:
                    time.sleep(.25)
                    delete_file(i)
                print "Filename: %r has printed" % i
                print
                time.sleep(.25)
                print                
        else:
            print "No files to print. Will retry in 15 seconds"
        time.sleep(15)


def print_file(pfile, printer):
    hinstance = win32api.ShellExecute(
        0,
        "print",
        '%s' % pfile,
        '/d:"%s"' % printer,
        ".",
        0
        )
    return hinstance


def delete_file(f):
    os.remove(f)
    print f, "was deleted!"

def alert(email):
    pass

main()
4

2 回答 2

6

使用ShellExecute,您将永远不知道打印何时完成,这取决于文件的大小以及打印机驱动程序是否缓冲内容(例如,打印机可能正在等待您填满纸盘)。

根据这个 SO answer,它看起来subprocess.call()是一个更好的解决方案,因为它等待命令完成,只有在这种情况下,您才需要读取注册表以获取与文件关联的 exe。

ShellExecuteEx可从pywin32获得,您可以执行以下操作:

import win32com.shell.shell as shell
param = '/d:"%s"' % printer
shell.ShellExecuteEx(fmask = win32com.shell.shellcon.SEE_MASK_NOASYNC, lpVerb='print', lpFile=pfile, lpParameters=param)

编辑:等待 ShellExecuteEx() 句柄的代码

import win32com.shell.shell as shell
import win32event
#fMask = SEE_MASK_NOASYNC(0x00000100) = 256 + SEE_MASK_NOCLOSEPROCESS(0x00000040) = 64
dict = shell.ShellExecuteEx(fMask = 256 + 64, lpFile='Notepad.exe', lpParameters='Notes.txt')
hh = dict['hProcess']
print hh
ret = win32event.WaitForSingleObject(hh, -1)
print ret
于 2013-08-03T07:53:58.750 回答
1

的返回值ShellExecute是你需要测试的。您从 中返回它print_file,但随后您忽略它。您需要捕获它并检查它。

hinstance = print_file(i, printer_name)
if hinstance > 32:
    ....

然而,让你的print_file函数泄漏实现细节HINSTANCE看起来很糟糕。我认为您最好在ShellExecute使用时直接检查返回值。所以试着把> 32支票往里挪print_file

请注意,ShellExecute错误报告非常弱。如果您想要正确的错误报告,那么您应该使用ShellExecuteEx

您的删除/睡眠循环确实非常脆弱。我不太确定我可以推荐更好的东西,因为我不确定你想要达到什么目标。但是,预计您的程序的那部分会遇到麻烦。

于 2013-08-02T20:56:38.023 回答