You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

28 lines
675 B
Python

2 years ago
import os
from fcntl import lockf, LOCK_EX, LOCK_UN
def get_edition_count(counter_path):
# Try to open a file descriptor to the given path
fd = os.open(counter_path, os.O_RDWR|os.O_CREAT)
# Lock the file so it can't be read in other processes
lockf(fd, LOCK_EX)
# Open the file and read
fo = os.fdopen(fd, 'r+', encoding='utf-8')
content = fo.read()
if not content:
edition_count = 0
else:
edition_count = int(content.strip())
edition_count += 1
# Clear file, write incremented value, unlock file and close
fo.seek(0)
fo.truncate()
fo.write(str(edition_count))
fo.flush()
lockf(fd, LOCK_UN)
os.close(fd)
return edition_count