2016-12-07 33 views
0

我編寫了應用程序,它從prestashop數據庫中獲取訂單詳細信息,將它們放到XML文件中,然後UPS WorldShip(用於發送UPS包裹的軟件)導入該XML文件並創建自己的out文件,結果作爲追蹤號碼。在接下來的步驟中,我將解析該退出文件以獲取跟蹤編號並將其保存在本地數據庫中。在Python中創建文件時讀取文件

我的問題是如何纔剛剛創建(.out)文件只有當它準備好(創建)。在這一刻我有這樣的代碼:

tree.write("C:/ProgramData/UPS/WSTD/IMPEXP/XML Auto Import/" + today + "-" + order_id + ".xml", encoding="utf-8", xml_declaration=True) 
time.sleep(1) 
out_file = etree.parse("C:/ProgramData/UPS/WSTD/IMPEXP/XML Auto Import/" + today + "-" + order_id + ".out") 

而這是不好的解決方案。我想「等到文件將被創建」。

我知道在python中是功能isfile()哪個檢查文件是否存在,但是我不知道如何檢查,直到它實際上會有。

+0

請參閱['watchdog'](https://pypi.python.org/pypi/watchdog)「,瞭解系統事件的跨平臺,基於事件的監視。或者只是在顯式循環中使用老式的輪詢。 –

回答

3

最簡單的辦法是輪詢。這裏我從Selenium的WebDriverWait課程中汲取靈感。

from time import time, sleep 

class Waiter(object): 
    def __init__(self, poll=0.5, timeout=60): 
     self.poll = poll 
     self.timeout = timeout 

    def until(self, callable, message='Timed out'): 
     end_time = time() + self.timeout 

     while True: 
      value = callable() 
      if value: 
       break 

      sleep(self.poll) 

      if time() > end_time: 
       raise Exception(message) 

要使用上面的類,就對其進行初始化,並通過一個可調用其until()方法。

import os 
wait = Waiter() 
wait.until(lambda: os.path.exists('fake.txt')) 
+0

謝謝,這就是我一直在尋找的東西 – user3041764

0

一個可能的解決方案可能會繼續檢查輸出目錄中的文件列表:列表更改時意味着您添加了可處理的新文件。

僞代碼:

import os 

checked_files = [] 

while(1): 

    all_files = os.listdir(output_folder) 
    new_files = set(all_files) - set(checked_files) 

    for file in new_files: 
     # Process them 
     .... 

    checked_files = all_files