#!/usr/bin/python -S # Copyright (C) 2012 Roman Zimbelmann # This software is distributed under the terms of the GNU GPL version 3. """ rifle, the file executor/opener of ranger This can be used as a standalone program or can be embedded in python code. When used together with ranger, it doesn't have to be installed to $PATH. Example usage: rifle = Rifle("rilfe.conf") rifle.reload_config() rifle.execute(["file1", "file2"]) """ import os.path import re from subprocess import Popen, PIPE import sys # Options and constants that a user might want to change: DEFAULT_PAGER = 'less' DEFAULT_EDITOR = 'nano' ASK_COMMAND = 'ask' ENCODING = 'utf-8' # Imports from ranger library, plus reimplementations in case ranger is not # installed so rifle can be run as a standalone program. try: from ranger.ext.get_executables import get_executables except ImportError: _cached_executables = None def get_executables(): """ Return all executable files in $PATH + Cache them. """ global _cached_executables if _cached_executables is not None: return _cached_executables if 'PATH' in os.environ: paths = os.environ['PATH'].split(':') else: paths = ['/usr/bin', '/bin'] from stat import S_IXOTH, S_IFREG paths_seen = set() _cached_executables = set() for path in paths: if path in paths_seen: continue paths_seen.add(path) try: content = os.listdir(path) except OSError: continue for item in content: abspath = path + '/' + item try: filestat = os.stat(abspath) except OSError: continue if filestat.st_mode & (S_IXOTH | S_IFREG): _cached_executables.add(item) return _cached_executables try: from ranger.ext.popen_forked import Popen_forked except ImportError: def Popen_forked(*args, **kwargs): """ Forks process and runs Popen with the given args and kwargs. """ try: pid = os.fork() except OSError: return False if pid == 0: os.setsid() kwargs['stdin'] = open(os.devnull, 'r') kwargs['stdout'] = kwargs['stderr'] = open(os.devnull, 'w') Popen(*args, **kwargs) os._exit(0) return True def _is_terminal(): # Check if stdin (file descriptor 0), stdout (fd 1) and # stderr (fd 2) are connected to a terminal try: os.ttyname(0) os.ttyname(1) os.ttyname(2) except: return False return True def squash_flags(flags): """ Remove lowercase flags if the respective uppercase flag exists >>> squash_flags('abc') 'abc' >>> squash_flags('abcC') 'ab' >>> squash_flags('CabcAd') 'bd' """ exclude = ''.join(f.upper() + f.lower() for f in flags if f == f.upper()) return ''.join(f for f in flags if f not in exclude) class Rifle(object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