python - 如何使用 hinstance 确定 win32api.ShellExecute 是否成功?

标签 python winapi python-2.7 pywin32 shellexecute

我一直在寻找我的原始问题的答案。我如何确定(以编程方式)我的 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() 命令以 try catch 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()

最佳答案

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

根据 this 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)

编辑:WAITING 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

关于python - 如何使用 hinstance 确定 win32api.ShellExecute 是否成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18025882/

相关文章:

python - Trac 插件不工作

WinAPI C++ 客户端在读取之前检测匿名管道上的写入

winapi - 如何使用 Vb6 中的 SHGetKnownFolderPath 函数

python - 当 URL 不存在时 Python 请求模块中的错误处理

python - 如何缩短多个 IF .... IN ... OR 语句?

python - QThread:在Python中线程仍在运行时被销毁

python - 在docker容器内调用命令

python - 如何使用 python 和 opencv 从彼此中减去两个图像?

c - 回溯时如何获取文件名和行号?

python - 040和40的区别