如何使用hinstance确定win32api.ShellExecute是否成功?
问题内容:
我一直在寻找原始问题的答案..如何确定(以编程方式)我的win32api.ShellExecute语句成功执行,并且如果成功执行,则执行os.remove()语句。
经过研究,我发现ShellExecute()调用返回了HINSTANCE。进一步的挖掘发现,如果成功,ShellExecute()将返回HINSTANCE>
32。我现在的问题是,如何使用它来控制程序的其余部分?我尝试使用一条if HINSTANCE> 32:
语句来控制下一部分,但是得到了一条NameError: name 'hinstance' is not defined
消息。通常,这不会使我感到困惑,因为这意味着我需要在引用变量“
hinstance”之前先定义它;但是,因为我认为ShellExecute应该返回HINSTANCE,所以我认为它可以使用吗?
这是我尝试执行此操作的完整代码。请注意,在我的print_file()定义中,我正在将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()
问题答案:
使用ShellExecute
,您将永远不会知道何时完成打印,这取决于文件的大小以及打印机驱动程序是否缓冲内容(例如,打印机可能正在等待您填充纸盒)。
根据此SO答案,这似乎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