Cyb*_*rai 3 python winapi pywin32 shellexecute python-2.7
我一直在寻找原始问题的答案..如何(以编程方式)确定我的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()
Run Code Online (Sandbox Code Playgroud)
使用时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)
Run Code Online (Sandbox Code Playgroud)
编辑:从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
Run Code Online (Sandbox Code Playgroud)