我用 Python 创建了一个看门狗。它监视一个文件夹 (test_folder)。如果创建了某个文件,我调用一个函数打开文件并创建一个 jpeg,这是再次保存在 test_folder 中。
第一次迭代工作正常,但是当我上传不同的文件(不同的内容,甚至名称略有不同)时出现错误:
Event: C:/Users/WEL4HO/Desktop/test_folder\AD1__Sampling2000KHz_AEKi-0.parquet created!
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\WEL4HO\.conda\envs\anaconda\lib\threading.py", line 980, in _bootstrap_inner
self.run()
File "C:\Users\WEL4HO\.conda\envs\anaconda\lib\site-packages\watchdog\observers\api.py", line 205, in run
self.dispatch_events(self.event_queue)
File "C:\Users\WEL4HO\.conda\envs\anaconda\lib\site-packages\watchdog\observers\api.py", line 381, in dispatch_events
handler.dispatch(event)
File "C:\Users\WEL4HO\.conda\envs\anaconda\lib\site-packages\watchdog\events.py", line 271, in dispatch
self.on_any_event(event)
File "C:\Users\WEL4HO\Desktop\test_folder\watchdog3.py", line 34, in on_any_event
Final.GAF(event.src_path, 'test_watchdog.jpeg')
File "C:\Users\WEL4HO\Desktop\test_folder\Final.py", line 18, in GAF
df = pq.read_table(source=parquet_file).to_pandas()
File "C:\Users\WEL4HO\.conda\envs\anaconda\lib\site-packages\pyarrow\parquet\__init__.py", line 2737, in read_table
dataset = _ParquetDatasetV2(
File "C:\Users\WEL4HO\.conda\envs\anaconda\lib\site-packages\pyarrow\parquet\__init__.py", line 2340, in __init__
[fragment], schema=schema or fragment.physical_schema,
File "pyarrow\_dataset.pyx", line 870, in pyarrow._dataset.Fragment.physical_schema.__get__
File "pyarrow\error.pxi", line 144, in pyarrow.lib.pyarrow_internal_check_status
File "pyarrow\error.pxi", line 111, in pyarrow.lib.check_status
PermissionError: [WinError 32] Failed to open local file 'C:/Users/WEL4HO/Desktop/test_folder/AD1__Sampling2000KHz_AEKi-0.parquet'. Detail: [Windows error 32] The process cannot access the file because it is being used by another process.
这是我的看门狗:
import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import Final
import os
class OnMyWatch:
watchDirectory = r'C:/Users/WEL4HO/Desktop/test_folder'
def __init__(self):
self.observer = Observer()
def run(self):
event_handler = Handler()
self.observer.schedule(event_handler, self.watchDirectory, recursive = True)
self.observer.start()
try:
while True:
time.sleep(1)
except:
self.observer.stop()
self.observer.join()
class Handler(FileSystemEventHandler):
@staticmethod
def on_any_event(event):
if event.is_directory:
return None
elif event.event_type == 'created':
print(f'Event: {event.src_path} created!')
#folder event.src_path -> folder raw -> file
if event.src_path.endswith('Sampling2000KHz_AEKi-0.parquet'):
Final.GAF(event.src_path, 'GAF_photo.jpeg')
if __name__ == '__main__':
watch = OnMyWatch()
watch.run()
这是我调用函数的文件:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
from pyts.image import GramianAngularField
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
from pathlib import Path
from scipy.signal import savgol_filter
import pandas as pd
import datetime
def GAF (path, outputname):
Sampling_rate = 2000000 #' Ae sample rate'
parquet_file = path
#convert data into numpy array
df = pq.read_table(source=parquet_file).to_pandas()
acoustic_emission_1 = df.values # convert the data into numpy array
time = len(acoustic_emission_1)/(Sampling_rate) #process length
#downsampling
downsampling_rate = 90
acoustic_emission_1_clip= acoustic_emission_1[:len(acoustic_emission_1)-(len(acoustic_emission_1)%downsampling_rate)]
acoustic_emission_1_downsampled = acoustic_emission_1_clip.reshape(-1, downsampling_rate).mean(axis=1)
samplingrate_downsampled = (Sampling_rate)/(downsampling_rate)
#positive data in arr
arr = np.array([], dtype=np.uint16)
counter=0
negative_values=0
for x in np.nditer(acoustic_emission_1_downsampled):
if x < 0:
negative_values=negative_values+1
pass
else:
arr = np.append(arr, acoustic_emission_1_downsampled[counter])
counter=counter+1
#new samplingrate
u=(negative_values)/time
samplingrate_new=samplingrate_downsampled-u
#filter
window_length=int(round((len(arr)*0.285),0))
if (window_length % 2) == 0:
window_length=window_length+1
else:
pass
print ('window_length:',window_length)
y_filtered = savgol_filter(arr,window_length, 3)
print ('nach filter', len(y_filtered))
print ('Y filtered:', y_filtered)
#x-axis
length=len(y_filtered) #länge AE werte
x = np.array([], dtype=int) #array x achse (zeit) leer
counter=0
i=0
while i==0:
x = np.append(x, counter)
if counter == length-1:
break
counter=counter+1
print ('x achse:', len(x))
X=np.array([y_filtered, x], dtype=object)
print (X)
print (length)
# Transform the time series into Gramian Angular Fields
gasf = GramianAngularField(image_size=1000, method='summation')
X_gasf = gasf.transform(X)
# Show the images for the first time series
fig = plt.figure(figsize=(20, 10))
grid = ImageGrid(fig, 111,
nrows_ncols=(1, 1),
axes_pad=0.15,
share_all=True,
cbar_location="right",
cbar_mode="single",
cbar_size="7%",
cbar_pad=0.3,
)
images = [X_gasf[0]]
titles = ['Summation']
for image, title, ax in zip(images, titles, grid):
im = ax.imshow(image, cmap='rainbow', origin='lower')
ax.set_title(title, fontdict={'fontsize': 12})
ax.cax.colorbar(im)
ax.cax.toggle_label(True)
plt.suptitle('Gramian Angular Field', y=0.98, fontsize=16)
fig.savefig(outputname, dpi=300)
plt.close(fig)
del fig
del df
nvm,我修好了。我补充说:
init_size = -1
while True:
current_size = os.path.getsize(event.src_path)
if current_size == init_size:
break
else:
init_size = os.path.getsize(event.src_path)
time.sleep(2)
print("file copy has now finished")