监视文件夹和打印 - 不使用 "endless" while 循环的替代方法?

Monitoring a folder and printing - alternative methods not using an "endless" while loop?

所以,我写这篇文章是为了监视文件夹中的新图片并打印找到的任何图片。它有效,但我假设有更多 robust/efficient 方法来解决这个问题,因为我希望它一次 运行 5-6 小时。

我的主要问题是我不喜欢像这样使用 "open" while 循环....

有人会以不同的方式解决这个问题吗?如果可以,有没有人愿意解释一下?

import os
import glob
import win32com.client
import time
from pywinauto.findwindows    import find_window
from pywinauto.win32functions import SetForegroundWindow

printed = []
i = 10 

while i < 1000000000000000:

files = glob.glob("C://Users//pictures/*.jpg")
for filename in files:
    print filename
    try:
        if printed.index(str(filename)) >= 0:
            print printed.index(filename)
            print "Image found" 
    except ValueError:  
        printed.append(filename)  
        os.startfile(filename, "print")
        shell = win32com.client.Dispatch("WScript.Shell")
        time.sleep(2)
        SetForegroundWindow(find_window(title='Print Pictures'))   
        shell.AppActivate("Print Pictures")
        shell.SendKeys("{ENTER}")

i = i + 1
time.sleep(5)

link 下面是相关的post。您可以使用观察器来触发您的操作,而不是使用长时间循环。

How to detect new or modified files

非常感谢 scope 的评论,我已将我的打印行添加到示例中并且效果很好。下面为任何需要它的人发布代码,注释代码在发布的 link 代码中。现在整理其他一些东西....

import os

import win32file
import win32event
import win
import glob
import win32com.client
import time
from pywinauto.findwindows    import find_window
from pywinauto.win32functions import SetForegroundWindow




def print_photo(filename): 
    print filename
    filename = path_to_watch +"\" + filename[0]
    os.startfile(filename, "print")
    shell = win32com.client.Dispatch("WScript.Shell")
    time.sleep(2)
    SetForegroundWindow(find_window(title='Print Pictures'))   
    shell.AppActivate("Print Pictures")
    shell.SendKeys("{ENTER}")

path_to_watch = os.path.abspath ("C:\Users\Ciaran\Desktop\")


change_handle = win32file.FindFirstChangeNotification (
  path_to_watch,
  0,
  win32con.FILE_NOTIFY_CHANGE_FILE_NAME
)


try:

  old_path_contents = dict ([(f, None) for f in os.listdir     (path_to_watch)])
  while 1:
    result = win32event.WaitForSingleObject (change_handle, 500)


    if result == win32con.WAIT_OBJECT_0:
      new_path_contents = dict ([(f, None) for f in os.listdir     (path_to_watch)])
      added = [f for f in new_path_contents if not f in     old_path_contents]
      print_photo(added)
      deleted = [f for f in old_path_contents if not f in new_path_contents]
      if added: print "Added: ", ", ".join (added)
      if deleted: print "Deleted: ", ", ".join (deleted)

      old_path_contents = new_path_contents
      win32file.FindNextChangeNotification (change_handle)

finally:
  win32file.FindCloseChangeNotification (change_handle)