-
Notifications
You must be signed in to change notification settings - Fork 34
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix file write concurrency #578
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,34 @@ | ||
from datetime import datetime, date, timedelta | ||
import os | ||
import pytz | ||
import fcntl | ||
import numpy as np | ||
|
||
|
||
def read_from_file(filepath=None, mode='r', **kwargs) -> str: | ||
with open(filepath, mode, **kwargs) as f: | ||
text = f.read() | ||
return text | ||
|
||
|
||
def write_to_file(filepath=None, data=None, mode='w', **kwargs) -> int: | ||
''' | ||
Concurrency safe function for writing data to the file. | ||
Param mode: file open mode ('a' for appending, 'w' for writing) | ||
''' | ||
assert mode == 'w' or mode == 'a' | ||
|
||
with open(filepath, mode, **kwargs) as f: | ||
fcntl.flock(f, fcntl.LOCK_EX) | ||
written_characters = f.write(data) | ||
fcntl.flock(f, fcntl.LOCK_UN) | ||
return written_characters | ||
Comment on lines
+14
to
+25
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This question comes from my lack of knowledge: |
||
|
||
|
||
def append_to_file(filepath=None, data=None, mode='a', **kwargs): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Since it is strictly append -- might be good to take out kwarg and just pass in mode='a' util.to write_to_file |
||
return write_to_file(filepath, data, mode, **kwargs) | ||
|
||
|
||
def quantile_sorted(sorted_arr, quantile): | ||
# For small arrays (less than about 4000 items) np.quantile is significantly | ||
# slower than sorting the array and picking the quantile out by index. Computing | ||
|
@@ -121,4 +147,4 @@ def get_intervals(start_time, end_time, interval_length): | |
)) | ||
rounded_start_time = new_start_time | ||
|
||
return time_str_intervals | ||
return time_str_intervals |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe worth explicitly closing file