我制作了一个非常简单的python脚本来从ftp服务器上的特定文件夹中获取文件,使用xml并将它们转换为不同的xml格式。它目前约占50%的时间。由于某种原因它随机抛出
[Errno 13]权限被拒绝:' ../ inFile / cd_catalog.xml'在cd_catalog.xml上
在线
inTree = ET.parse(路径)
(其中path =' ../ inFile /' +(event.src_path).split(" \")[ - 1])
我每次都检查过路径,看起来效果很好。例如,如果文件' sample.xml'出现在' inFile'目录,路径将是' ../ inFile / simple.xml'每次。
现在由于某种原因,这种方法偶尔会有效,但不是每次都有效。它有时在重新启动后第一次尝试失败,所以我知道某些文件无法打开。
我对这种随机性感到困惑,任何远见都会受到高度赞赏。
import xml.etree.ElementTree as ET
import os
import sys
import datetime
import time
import shutil
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
###################################################################################
# Converts the XML file from the inFile folder and sends it to the outFile in
# the correct format.
###################################################################################
def convert_xml(path, name):
try:
print(path)
inTree = ET.parse(path) # ERROR HERE!!!!
inRoot = inTree.getroot()
date = datetime.datetime.now().strftime("%Y-%m-%d")
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M").replace(' ', '_').replace(':', '-')
if not os.path.exists("../outFile/" + date):
os.makedirs("../outFile/" + date)
print(name)
outRoot = ET.Element(name)
for elem in inRoot.getiterator():
ET.SubElement(outRoot, elem.tag).text = elem.text
# This is not the correct format but used to verify data can be pulled
#print(elem.tag, " - ", elem.text)
outTree = ET.ElementTree(outRoot)
print("../outFile/" + date + "/" + outRoot.tag)
outTree.write("../outFile/" + date + "/" + outRoot.tag)
except Exception as e:
write_to_log(name, "convert_xml: " + str(e))
print(type(e).__name__ + " on " + name)
print("convert_xml " + str(e) + " on " + name)
raise
###################################################################################
# Creates a log for the day if none is created and writes to it.
###################################################################################
def write_to_log(name, message):
try:
date = datetime.datetime.now().strftime("%Y-%m-%d")
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
f = open("Logs/" + date + ".txt", "a+")
f.write(now + " " + name + " " + message + "\n")
f.close()
except Exception as e:
print("write_to_log " + str(e) + " on " + name)
###################################################################################
# Check if any xml file was added to the inScript directory.
###################################################################################
class MyHandler(FileSystemEventHandler):
def on_created(self, event):
try:
name = (event.src_path).split("\\")[-1]
print('../inFile/' + name)
convert_xml('../inFile/' + name, name)
date = datetime.datetime.now().strftime("%Y-%m-%d")
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M").replace(' ', '_').replace(':', '-')
if not os.path.exists("../archive/" + date):
os.makedirs("../archive/" + date)
shutil.copy2(event.src_path, '../archive/' + date + "/" + now + "_" + name)
write_to_log(name, "SUCCESSFULLY RECEIVED")
print("Successfully received: " + name)
except Exception as e:
write_to_log(name, "on_created: " + str(e))
print("on_created " + str(e) + " on " + name)
write_to_log(name, "FAILURE")
print("Failure: " + name)
###################################################################################
# Main function
###################################################################################
if __name__ == "__main__":
if not os.path.exists("../inFile/"):
os.makedirs("../inFile")
if not os.path.exists("../outFile/"):
os.makedirs("../outFile")
if not os.path.exists("../archive/"):
os.makedirs("../archive")
if not os.path.exists("Logs"):
os.makedirs("Logs")
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path='F:\FTP\TransportationLogistics\inFile', recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
编辑:更多信息,如果我一次删除多个文件,第一个文件将100%失败,其他文件将100%完成。
EDIT2:在调试器模式下100%的时间工作,仍然混淆为什么会导致这种情况。是否与内存的分配方式有关?
EDIT3:我认为权限被拒绝错误是python中常见的拐杖。我假设Element Tree正在尝试修改文件夹属性,那就是在抛出错误时。我将尝试使用lxml而不是Element Tree进行xml解析。
问题是复制并粘贴到文件夹中。如果我只是简单地拖放就可以了,但是如果我复制并粘贴它,它偶尔会抛出错误,不知道是什么导致它,但我希望没有人每个副本和粘贴它。