【发布时间】:2013-08-02 20:49:12
【问题描述】:
我一直在寻找原始问题的答案。我如何(以编程方式)确定我的 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()
【问题讨论】:
-
ShellExecute返回一个HINSTANCE类型的值,与任何变量名无关。你还需要hinstance = print_file(...)。 -
啊哈!这是有道理的。现在看来,这对我来说是一个愚蠢的疏忽。谢谢你。我调整了代码,使 print_file 只运行
win32api.ShellExecute(...)而没有任何 hinstance 位,并将 main() 中的部分更改为就像您引用hinstance = print_file(...)但现在 print_file() 返回 None 而不是像以前那样的 42L。有什么想法吗? -
只有在print_file返回的情况下,调用者才能得到值
-
好的,我明白我做错了什么。我调整了我的
print_file()函数以返回 hinstance。所以现在 for 循环看起来像:pastebin.com/yTX461JT 你觉得怎么样? -
那个 pastebin 是 Drew 在他的评论中建议的,也是我在回答中写的。我觉得没有什么要补充的了,
标签: python winapi python-2.7 pywin32 shellexecute