def process_dialog_for_player(dialog_id, loop=False): _dialog = get_dialog(dialog_id) _dialog['choices'] = [] _dialog['loop_choices'] = [] _dialog['cursor_index'] = 0 _last_message = get_last_message(dialog_id) if loop: end_dialog(dialog_id) locks.lock('camera_free') return False for response in get_matching_message(LIFE[SETTINGS['controlling']], dialog_id, _last_message['next_gist']): _to_check = [response] while _to_check: _response = _to_check.pop() if _response['text'].startswith('>'): _text = reformat_text(LIFE[SETTINGS['controlling']], get_listener(dialog_id), dialog_id, _response['text'][1:]) _to_check.extend( get_matching_message(LIFE[SETTINGS['controlling']], dialog_id, _text)) _dialog['loop_choices'].extend(_to_check) else: _dialog['choices'].append(_response) _dialog['max_cursor_index'] = len(_dialog['choices'])
def process_dialog_for_player(dialog_id, loop=False): _dialog = get_dialog(dialog_id) _dialog['choices'] = [] _dialog['loop_choices'] = [] _dialog['cursor_index'] = 0 _last_message = get_last_message(dialog_id) if loop: end_dialog(dialog_id) locks.lock('camera_free') return False for response in get_matching_message(LIFE[SETTINGS['controlling']], dialog_id, _last_message['next_gist']): _to_check = [response] while _to_check: _response = _to_check.pop() if _response['text'].startswith('>'): _text = reformat_text(LIFE[SETTINGS['controlling']], get_listener(dialog_id), dialog_id, _response['text'][1:]) _to_check.extend(get_matching_message(LIFE[SETTINGS['controlling']], dialog_id, _text)) _dialog['loop_choices'].extend(_to_check) else: _dialog['choices'].append(_response) _dialog['max_cursor_index'] = len(_dialog['choices'])
def file_move_safe(old_file_name, new_file_name, chunk_size=1024 * 64, allow_overwrite=False): """ Moves a file from one location to another in the safest way possible. First, tries ``os.rename``, which is simple but will break across filesystems. If that fails, streams manually from one file to another in pure Python. If the destination file exists and ``allow_overwrite`` is ``False``, this function will throw an ``IOError``. """ # There's no reason to move if we don't have to. if _samefile(old_file_name, new_file_name): return try: # If the destination file exists and allow_overwrite is False then raise an IOError if not allow_overwrite and os.access(new_file_name, os.F_OK): raise IOError( "Destination file %s exists and allow_overwrite is False" % new_file_name) os.rename(old_file_name, new_file_name) return except OSError: # This will happen with os.rename if moving to another filesystem # or when moving opened files on certain operating systems pass # first open the old file, so that it won't go away with open(old_file_name, 'rb') as old_file: # now open the new file, not forgetting allow_overwrite fd = os.open(new_file_name, (os.O_WRONLY | os.O_CREAT | getattr(os, 'O_BINARY', 0) | (os.O_EXCL if not allow_overwrite else 0))) try: locks.lock(fd, locks.LOCK_EX) current_chunk = None while current_chunk != b'': current_chunk = old_file.read(chunk_size) os.write(fd, current_chunk) finally: locks.unlock(fd) os.close(fd) copystat(old_file_name, new_file_name) try: os.remove(old_file_name) except OSError as e: # Certain operating systems (Cygwin and Windows) # fail when deleting opened files, ignore it. (For the # systems where this happens, temporary files will be auto-deleted # on close anyway.) if getattr(e, 'winerror', 0) != 32 and getattr(e, 'errno', 0) != 13: raise
def process(life, dialog_id): if not is_turn_to_talk(life, dialog_id): return False _last_message = get_last_message(dialog_id) if _last_message['next_gist'] == 'end': end_dialog(dialog_id) locks.lock('camera_free') elif 'player' in life: locks.unlock('camera_free', reason='Process dialog') process_dialog_for_player(dialog_id, loop=_last_message['loop']) else: say_via_gist(life, dialog_id, _last_message['next_gist'], loop=_last_message['loop'])
def show_next_event(): if not EVENTS: return False _event = None for event in EVENTS: if not event['delay']: _event = event break if not _event: return False EVENTS.remove(_event) gfx.refresh_view('map') if not EVENTS: life.focus_on(LIFE[SETTINGS['following']]) locks.lock('camera_free', reason='No more events') return False return True
def __init__(self, torrent): self.torrent = torrent self.left = torrent.length self.peer_id = os.urandom(20) self.port = 6882 self.uploaded = 0 self.downloaded = 0 self.finished = False self.chunk_queue = [] self.chunks_left = [] self.data_left = 0 self.data = bytearray(torrent.length) self.lock = locks.lock()
def bot(): try: logger.debug("Checking if script already run...") logger.debug(" testing lock of " + flockd_name) f = os.open(flockd_name, os.O_TRUNC | os.O_CREAT | os.O_RDWR) fres = locks.lock(f, locks.LOCK_EX + locks.LOCK_NB) if fres: logger.debug(" bot is not active") main() else: logger.debug("Script already running...") except IOError: logger.debug("Bot is already running") except Exception as inst: logger.error(type(inst)) logger.error(inst.args) logger.error(inst) else: logger.debug("Exiting script and unlocking") locks.unlock(f) os.close(f) os.remove(flockd_name) logger.debug("Bot is off...")
parser = argparse.ArgumentParser(add_help=True, description='Telegram bot') parser.add_argument("-d", "--daemon", action="store_true", help="run as daemon, only Linux") parser.add_argument("-v", "--verbose", action="store_true", help="detailed/debug log") args = parser.parse_args() logger = tg_logger.initLogger(args.verbose) logger.debug("Checking if script already run...") logger.debug(" testing lock of " + flockm_name) fm = os.open(flockm_name, os.O_TRUNC | os.O_CREAT | os.O_RDWR) fmres = locks.lock(fm, locks.LOCK_EX + locks.LOCK_NB) if fmres: #main is not run logger.debug(" check if daemon is run: " + flockd_name) fd = os.open(flockd_name, os.O_TRUNC | os.O_CREAT | os.O_RDWR) fdres = locks.lock(fd, locks.LOCK_EX + locks.LOCK_NB) if fdres: #not run - unlock and re-run as daemon locks.unlock(fd) logger.debug("dAemonize bot...") if args.daemon: if os.name == 'nt': logger.warning( "daemon mode is not supported in Windows") else: with daemon.DaemonContext( files_preserve=tg_logger.logger_handlers): bot()
def _save(self, name, content): full_path = self.path(name) # Create any intermediate directories that do not exist. # Note that there is a race between os.path.exists and os.makedirs: # if os.makedirs fails with EEXIST, the directory was created # concurrently, and we can continue normally. Refs #16082. directory = os.path.dirname(full_path) if not os.path.exists(directory): try: if self.directory_permissions_mode is not None: # os.makedirs applies the global umask, so we reset it, # for consistency with file_permissions_mode behavior. old_umask = os.umask(0) try: os.makedirs(directory, self.directory_permissions_mode) finally: os.umask(old_umask) else: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise if not os.path.isdir(directory): raise IOError("%s exists and is not a directory." % directory) # There's a potential race condition between get_available_name and # saving the file; it's possible that two threads might return the # same name, at which point all sorts of fun happens. So we need to # try to create the file, but if it already exists we have to go back # to get_available_name() and try again. while True: try: # This file has a file path that we can move. if hasattr(content, 'temporary_file_path'): shutil.move(content.temporary_file_path(), full_path) # This is a normal uploadedfile that we can stream. else: # This fun binary flag incantation makes os.open throw an # OSError if the file already exists before we open it. flags = (os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_BINARY', 0)) # The current umask value is masked out by os.open! fd = os.open(full_path, flags, 0o666) _file = None try: locks.lock(fd, locks.LOCK_EX) for chunk in content.chunks(): if _file is None: mode = 'wb' if isinstance(chunk, bytes) else 'wt' _file = os.fdopen(fd, mode) _file.write(chunk) finally: locks.unlock(fd) if _file is not None: _file.close() else: os.close(fd) except OSError as e: if e.errno == errno.EEXIST: # Ooops, the file exists. We need a new file name. name = self.get_available_name(name) full_path = self.path(name) else: raise else: # OK, the file save worked. Break out of the loop. break if self.file_permissions_mode is not None: os.chmod(full_path, self.file_permissions_mode) return name