rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
statuses = TdbqPredicate(lambda au: au.status() in [AU.STATUS_EXISTS, AU.STATUS_MANIFEST, AU.STATUS_WANTED, AU.STATUS_TESTING, AU.STATUS_NOT_READY, AU.STATUS_TESTED, AU.STATUS_RETESTING, AU.STATUS_READY, AU.STATUS_PRE_RELEASING, AU.STATUS_PRE_RELEASED, AU.STATUS_RELEASING, AU.STATUS_RELEASED, AU.STATUS_DOWN, AU.STATUS_SUPERSEDED, AU.STATUS_RETRACTED])
statuses = TdbqPredicate(lambda au: au.status() in [AU.Status.EXISTS, AU.Status.MANIFEST, AU.Status.WANTED, AU.Status.TESTING, AU.Status.NOT_READY, AU.Status.TESTED, AU.Status.RETESTING, AU.Status.READY, AU.Status.PRE_RELEASING, AU.Status.PRE_RELEASED, AU.Status.RELEASING, AU.Status.RELEASED, AU.Status.DOWN, AU.Status.SUPERSEDED, AU.Status.RETRACTED])
def tdbq_reprocess(tdb, options): '''Reprocesses a Tdb instance according to the query that may be included in the options. Returns the same Tdb instance if there is no query.''' if not (options.testingStatuses or options.productionStatuses or options.query): return tdb query = None if options.query: query = TdbqParser(TdbqScanner(options.query, options), options).parse() statuses = None if options.productionStatuses: statuses = TdbqPredicate(lambda au: au.status() in [AU.STATUS_RELEASED, AU.STATUS_DOWN, AU.STATUS_SUPERSEDED, AU.STATUS_RETRACTED]) elif options.testingStatuses: statuses = TdbqPredicate(lambda au: au.status() in [AU.STATUS_EXISTS, AU.STATUS_MANIFEST, AU.STATUS_WANTED, AU.STATUS_TESTING, AU.STATUS_NOT_READY, AU.STATUS_TESTED, AU.STATUS_RETESTING, AU.STATUS_READY, AU.STATUS_PRE_RELEASING, AU.STATUS_PRE_RELEASED, AU.STATUS_RELEASING, AU.STATUS_RELEASED, AU.STATUS_DOWN, AU.STATUS_SUPERSEDED, AU.STATUS_RETRACTED]) if query and statuses: prog = TdbqAnd(query, statuses) elif query: prog = query else: prog = statuses newtdb = Tdb() for au in tdb.aus(): if prog.keep_au(au): newtdb.add_au(au) if au.title() not in newtdb.titles(): newtdb.add_title(au.title()) if au.title().publisher() not in newtdb.publishers(): newtdb.add_publisher(au.title().publisher()) return newtdb
if (auid[0].find("HighWire") != -1) and (auid[0].find("royalsocietypublishing") != 0):
if (auid[0].find("HighWire") != -1) and (auid[0].find("royalsocietypublishing") != -1):
def _main_procedure(): parser = _make_command_line_parser() (options, args) = parser.parse_args(values=parser.get_default_values()) _check_required_options(parser, options) db = MySQLdb.connect(host="localhost", user="edwardsb", passwd=options.dbpassword, db="burp") _update_required_options(db, options) # Initialize the hashes. # WARNING: If you update this list, you need to update three places: # 1. The list of publishers in the 'while auid is not None' loop. # 2. The summary report # 3. In BurpCheck.py, the _is_reported() method. publishers = ['aap', 'aip', 'ama', 'aps', 'acm', 'bep', 'bmc', 'cap', 'eup', 'elsevier', 'gtv', 'iop', 'wiley', 'lup', 'npg', 'oup', 'rup', 'rsc', 'rsp', 'sage', 'springer', 'ssr', 'tf'] total = {} pubyear = {} for publisher in publishers: pubyear[publisher] = {} total[publisher] = 0 for year in range(options.currentyear, options.minimumyear - 1, -1) + ["0"]: strYear = str(year) pubyear[publisher][strYear] = 0 cursorAuid = db.cursor() cursorAuid.execute("SELECT DISTINCT(auid) from burp WHERE rundate >= '" + str(options.reportdatestart) + "' AND rundate <= '" + str(options.reportdateend) + "' order by auid;") auid = cursorAuid.fetchone() while auid is not None: cursorArticles = db.cursor() cursorArticles.execute("SELECT MAX(numarticles), auyear FROM burp WHERE auid = \"" + auid[0] + "\" and rundate >= '" + str(options.reportdatestart) + "' AND rundate <= '" + str(options.reportdateend) +"';") articles = cursorArticles.fetchone() strYear = articles[1] if "-" in strYear: strYear = strYear[5:9] # If you change this list, be sure to change the equivalent # list in BurpCheck.py. if (auid[0].find("ClockssHighWirePlugin") != -1) and (auid[0].find("aappublications") != -1): pubyear['aap'][strYear] += articles[0] total['aap'] += articles[0] # No criteria for American Institute of Physics. if (auid[0].find("ClockssHighWirePlugin") != -1) and (auid[0].find("ama-assn") != -1): pubyear['ama'][strYear] += articles[0] total['ama'] += articles[0] if (auid[0].find("ClockssHighWirePlugin") != -1) and (auid[0].find("physiology%2Eorg") != -1): pubyear['aps'][strYear] += articles[0] total['aps'] += articles[0] # No criteria for Association for Computing Machinery if (auid[0].find("ClockssBerkeleyElectronicPressPlugin") != -1): pubyear['bep'][strYear] += articles[0] total['bep'] += articles[0] # No criteria for BioMed Central. if (auid[0].find("ClockssCoActionPublishingPlugin") != -1): pubyear['cap'][strYear] += articles[0] total['cap'] += articles[0] if (auid[0].find("ClockssEdinburghUniversityPressPlugin") != -1): pubyear['eup'][strYear] += articles[0] total['eup'] += articles[0] # No criteria for Elsevier. if (auid[0].find("ClockssGeorgThiemeVerlagPlugin") != -1): pubyear['gtv'][strYear] += articles[0] total['gtv'] += articles[0] # No criteria for IOP Publishing # No criteria for Wiley # No criteria for Liverpool if (auid[0].find("ClockssNaturePublishingGroupPlugin") != -1): pubyear['npg'][strYear] += articles[0] total['npg'] += articles[0] if (auid[0].find("HighWire") != -1) and (auid[0].find("oxfordjournals") != -1): pubyear['oup'][strYear] += articles[0] total['oup'] += articles[0] # No criteria for Rockefeller University Press if (auid[0].find("ClockssRoyalSocietyOfChemistryPlugin") != -1): pubyear['rsc'][strYear] += articles[0] total['rsc'] += articles[0] if (auid[0].find("HighWire") != -1) and (auid[0].find("royalsocietypublishing") != 0): pubyear['rsp'][strYear] += articles[0] total['rsp'] += articles[0] if (auid[0].find("HighWire") != -1) and (auid[0].find("sagepub") != -1): pubyear['sage'][strYear] += articles[0] total['sage'] += articles[0] # No criteria for Springer if (auid[0].find("HighWire") != -1) and (auid[0].find("biolreprod%2Eorg") != -1): pubyear['ssr'][strYear] += articles[0] total['ssr'] += articles[0] # No criteria for Taylor & Francis auid = cursorAuid.fetchone() # Verify our numbers! for publisher in publishers: testTotal = 0 for year in range(options.currentyear, options.minimumyear - 1, -1) + ["0"]: strYear = str(year) testTotal += pubyear[publisher][strYear] if total[publisher] != testTotal: print "ERROR: Publisher " + publisher + " doesn't have the right total." # Post the report to the database for publisher in publishers: for year in range(options.currentyear, options.minimumyear - 1, -1) + [0]: strYear = str(year) cursorAuid.execute("INSERT INTO burpreport(rundate, publisher, auyear, numarticles) VALUES (NOW(), \"%s\", %d, %d);" % (publisher, year, pubyear[publisher][strYear])) # Output the main report. filename = open(options.filename, 'w') filename.write("Dates of ingest," + str(options.reportdatestart) + " - " + str(options.reportdateend) + "\n") filename.write("Date of report," + str(date.today()) + "\n") filename.write("year,") for publisher in publishers: filename.write(publisher.upper() + ",") # Yes, there's an extra comma at the end. Same with everything else. # If that's a problem, we can fix it. filename.write("\n"); for year in range(options.currentyear, options.minimumyear - 1, -1) + ["0"]: strYear = str(year) printYear = strYear if (year == options.currentyear): printYear = "Current Ingest " + strYear if (year == "0"): printYear = "Data entry in progress -- Year TBD" filename.write( printYear + "," ) for publisher in publishers: filename.write(str(pubyear[publisher][strYear]) + ",") filename.write("\n") filename.write("Back Ingest Total,") for publisher in publishers: filename.write(str(total[publisher]) + ",") filename.write("\n") # Output the new summary report. # WARNING: I don't have a simple way to keep track of names compared # against publishers. You need to update these in two places: the # list called 'publishers' and here. currentyear = str(options.currentyear) summary = open(options.summary, "w") summary.write("Official Publisher Name,Publisher ID, Total Ingest for " + str(currentyear) + ", Total Ingest For all time\n") _print_summary_line(summary, "American Academy of Pediatrics", "aap", currentyear, pubyear, total) _print_summary_line(summary, "American Institute of Physics", "aip", currentyear, pubyear, total) _print_summary_line(summary, "American Medical Association", "ama", currentyear, pubyear, total) _print_summary_line(summary, "American Physiological Society", "aps", currentyear, pubyear, total) _print_summary_line(summary, "Association for Computing Machinery", "acm", currentyear, pubyear, total) _print_summary_line(summary, "Berkeley Electronic Press", "bep", currentyear, pubyear, total) _print_summary_line(summary, "BioMed Central", "bmc", currentyear, pubyear, total) _print_summary_line(summary, "Co-Action Publishing", "cap", currentyear, pubyear, total) _print_summary_line(summary, "Edinburgh University Press", "eup", currentyear, pubyear, total) _print_summary_line(summary, "Elsevier", "elsevier", currentyear, pubyear, total) _print_summary_line(summary, "Georg Thieme Verlag", "gtv", currentyear, pubyear, total) _print_summary_line(summary, "IOP Publishing", "iop", currentyear, pubyear, total) _print_summary_line(summary, "John Wiley and Sons", "wiley", currentyear, pubyear, total) _print_summary_line(summary, "Liverpool University Press", "lup", currentyear, pubyear, total) _print_summary_line(summary, "Nature Publishing Group", "npg", currentyear, pubyear, total) _print_summary_line(summary, "Oxford University Press", "oup", currentyear, pubyear, total) _print_summary_line(summary, "Rockefeller University Press", "rup", currentyear, pubyear, total) _print_summary_line(summary, "RSC Publishing", "rsc", currentyear, pubyear, total) _print_summary_line(summary, "Royal Society Publishing", "rsp", currentyear, pubyear, total) _print_summary_line(summary, "SAGE Publications", "sage", currentyear, pubyear, total) _print_summary_line(summary, "Springer", "springer", currentyear, pubyear, total) _print_summary_line(summary, "Society for the Study of Reproduction", "ssr", currentyear, pubyear, total) _print_summary_line(summary, "Taylor and Francis", "tf", currentyear, pubyear, total)
if re.match(re.compile('(' + '|'.join([TdbqLiteral.AND, TdbqLiteral.OR, TdbqLiteral.IS, TdbqLiteral.NOT, TdbqLiteral.SET]) + ') '), self.__str):
if re.match(re.compile('(' + '|'.join([TdbqLiteral.AND, TdbqLiteral.OR, TdbqLiteral.IS, TdbqLiteral.NOT, TdbqLiteral.SET]) + ')([ )]|$)'), self.__str):
def next(self): '''Consumes and returns one token from the input string. Returns a token of type TdbqToken.END_OF_STRING the first time the end of the query string is reached, and raises a runtime exception thereafter.''' # Already at end of string if self.__cur.type() == TdbqToken.END_OF_STRING: raise RuntimeError, 'already at end of string' # Skip whitespace match = re.match(TdbqLiteral.RE_WHITESPACE, self.__str) if match: self.__move(match.end()) # End of input if self.__str == '': self.__token(TdbqToken.END_OF_STRING) return self.__cur # Literal if re.match(re.compile('|'.join([TdbqLiteral.EQUAL, TdbqLiteral.NOT_EQUAL, TdbqLiteral.MATCHES, TdbqLiteral.DOES_NOT_MATCH, '\\' + TdbqLiteral.PAREN_OPEN, '\\' + TdbqLiteral.PAREN_CLOSE])), self.__str): return self.__literal() # Keyword if re.match(re.compile('(' + '|'.join([TdbqLiteral.AND, TdbqLiteral.OR, TdbqLiteral.IS, TdbqLiteral.NOT, TdbqLiteral.SET]) + ') '), self.__str): return self.__keyword() # String if self.__str.startswith(TdbqLiteral.QUOTE_DOUBLE): return self.__dquote() if self.__str.startswith(TdbqLiteral.QUOTE_SINGLE): return self.__squote() # Identifier match = re.match(TdbqLiteral.RE_IDENTIFIER, self.__str) if match: self.__token(TdbqToken.IDENTIFIER) self.__move(match.end()) self.__cur.set_value(match.group()) return self.__cur # Syntax error self.__token(TdbqToken.NONE) raise RuntimeError, 'syntax error at index %d near: %s' % (self.__ind, self.__str)
raise RuntimeError, 'expected "%s", "%s", "%s", "%s",or "%s" at index %d but got: %s' % (TdbqLiteral.IS, TdbqLiteral.EQUAL, TdbqLiteral.NOT_EQUAL, TdbqLiteral.MATCHES, TdbqLiteral.DOES_NOT_MATCH, oper.index(), oper.translate())
raise RuntimeError, 'expected "%s", "%s", "%s", "%s" or "%s" at index %d but got: %s' % (TdbqLiteral.IS, TdbqLiteral.EQUAL, TdbqLiteral.NOT_EQUAL, TdbqLiteral.MATCHES, TdbqLiteral.DOES_NOT_MATCH, oper.index(), oper.translate())
def __expression(self): '''expression : TdbqToken.PAREN_OPEN or_expression TdbqToken.PAREN_CLOSE | TdbqToken.IDENTIFIER TdbqToken.IS TdbqToken.NOT? ( TdbqToken.SET | TdbqToken.STRING ) | TdbqToken.IDENTIFIER ( TdbqToken.EQUAL | TdbqToken.NOT_EQUAL | TdbqToken.MATCHES | TdbqToken.DOES_NOT_MATCH ) TdbqToken.STRING ;''' if self.__accept(TdbqToken.PAREN_OPEN): self.__or_expression() self.__expect(TdbqToken.PAREN_CLOSE, self.__input[self.__ind].index()) return # Identifier ident = self.__input[self.__ind] self.__expect(TdbqToken.IDENTIFIER, ident.index()) func_ident = str_to_lambda_au(ident.value()) if func_ident is None: raise RuntimeError, 'bad identifier at index %d: %s' % (ident.index(), ident.value()) # Operator, or "is" and optional "not" oper = self.__input[self.__ind] opertyp = oper.type() if self.__accept(TdbqToken.IS): if self.__accept(TdbqToken.NOT): opertyp = TdbqToken.NOT_EQUAL else: opertyp = TdbqToken.EQUAL elif opertyp in [TdbqToken.EQUAL, TdbqToken.NOT_EQUAL, TdbqToken.MATCHES, TdbqToken.DOES_NOT_MATCH]: self.__expect(opertyp, oper.index()) else: raise RuntimeError, 'expected "%s", "%s", "%s", "%s",or "%s" at index %d but got: %s' % (TdbqLiteral.IS, TdbqLiteral.EQUAL, TdbqLiteral.NOT_EQUAL, TdbqLiteral.MATCHES, TdbqLiteral.DOES_NOT_MATCH, oper.index(), oper.translate())
e_url = node.getElementsByTagName("url")[0].childNodes[0].data e_title = node.getElementsByTagName("title")[0].childNodes[0].data e_artist = node.getElementsByTagName("artist")[0].childNodes[0].data e_album = node.getElementsByTagName("album")[0].childNodes[0].data
tmp = node.getElementsByTagName("url") if tmp == []: e_url = 0 else: if tmp[0].childNodes == []: e_url = 0; else: e_url = tmp[0].childNodes[0].data tmp = node.getElementsByTagName("title") if tmp == []: e_title = 0 else: if tmp[0].childNodes == []: e_title = 0; else: e_title = tmp[0].childNodes[0].data tmp = node.getElementsByTagName("artist") if tmp == []: e_artist = 0 else: if tmp[0].childNodes == []: e_artist = 0; else: e_artist = tmp[0].childNodes[0].data tmp = node.getElementsByTagName("album") if tmp == []: e_album = 0 else: if tmp[0].childNodes == []: e_album = 0; else: e_album = tmp[0].childNodes[0].data tmp = node.getElementsByTagName("tag") if tmp == []: e_genre = 0 else: if tmp[0].childNodes == []: e_genre = 0; else: e_genre = tmp[0].childNodes[0].data
def load_db(self): import urllib2 import time import md5 import xml.dom.minidom
self.db.set(e, rhythmdb.PROP_GENRE, e_genre)
def load_db(self): import urllib2 import time import md5 import xml.dom.minidom
content = cat(object_provides=IDynamicType.__identifier__)
query = {'object_provides': IDynamicType.__identifier__} if HAS_LINGUAPLONE: query['Language'] = 'all' content = cat(query)
def register_all_content_for_intids(portal): """Registers all existing content with the intid utility. This will not be fast.""" cat = getToolByName(portal, 'portal_catalog', None) intids = getUtility(IIntIds) register = intids.register # Take advantage of paths stored in keyreferences in five.intid to optimize # registration registered_paths = dict((ref.path,None) for ref in intids.ids if hasattr(ref, 'path')) # Count how many objects we register registered = 0 existing = 0 if cat is not None: content = cat(object_provides=IDynamicType.__identifier__) for brain in content: if brain.getPath() in registered_paths: existing += 1 continue try: obj = brain.getObject() register(obj) registered += 1 except (AttributeError, KeyError): pass return registered, existing
db[sha1] = urlparse.urljoin(uri, path)
db[sha1] = '%s/%s' % (uri.rstrip('/'), path)
def _PopulateDuplicateDB(self, db): """Populate db with SHA1 -> URL mapping for packages.
pkg['PATH'] = urlparse.urljoin(path_prefix, pkg['CPV'] + '.tbz2')
pkg['PATH'] = '%s/%s' % (path_prefix.rstrip('/'), pkg['CPV'] + '.tbz2')
def SetUploadLocation(self, base_uri, path_prefix): """Set upload location to base_uri + path_prefix.
url = urlparse.urljoin(binhost_url, 'Packages')
url = '%s/Packages' % binhost_url.rstrip('/')
def GrabRemotePackageIndex(binhost_url): """Grab the latest binary package database from the specified URL. Args: binhost_url: Base URL of remote packages (PORTAGE_BINHOST). Returns: A PackageIndex object, if the Packages file can be retrieved. If the server returns status code 404, None is returned. """ url = urlparse.urljoin(binhost_url, 'Packages') try: f = _RetryUrlOpen(url) except urllib2.HTTPError as e: if e.code == 404: return None raise pkgindex = PackageIndex() pkgindex.Read(f) pkgindex.header.setdefault('URI', binhost_url) f.close() return pkgindex
path = pkg.get('PATH', cpv + '.tbz2')
path = pkg.get('PATH', urllib.quote(cpv + '.tbz2'))
def _PopulateDuplicateDB(self, db): """Populate db with SHA1 -> URL mapping for packages.
pkg['PATH'] = '%s/%s' % (path_prefix.rstrip('/'), pkg['CPV'] + '.tbz2')
path = urllib.quote(pkg['CPV'] + '.tbz2') pkg['PATH'] = '%s/%s' % (path_prefix.rstrip('/'), path)
def SetUploadLocation(self, base_uri, path_prefix): """Set upload location to base_uri + path_prefix.
cpv, sha1 = pkg['CPV'], pkg['SHA1'] path = pkg.get('PATH', cpv + '.tbz2') db[sha1] = urlparse.urljoin(uri, path)
cpv, sha1 = pkg['CPV'], pkg.get('SHA1') if sha1: path = pkg.get('PATH', cpv + '.tbz2') db[sha1] = urlparse.urljoin(uri, path)
def _PopulateDuplicateDB(self, db): """Populate db with SHA1 -> URL mapping for packages.
sha1 = pkg['SHA1']
sha1 = pkg.get('SHA1')
def ResolveDuplicateUploads(self, pkgindexes): """Point packages at files that have already been uploaded.
if uri and uri.startswith(base_uri):
if sha1 and uri and uri.startswith(base_uri):
def ResolveDuplicateUploads(self, pkgindexes): """Point packages at files that have already been uploaded.
proc = subprocess.Popen(cmd_str, cwd=cwd, stdin=stdin, stdout=stdout, stderr=stderr, shell=shell)
proc = subprocess.Popen(cmd, cwd=cwd, stdin=stdin, stdout=stdout, stderr=stderr, shell=shell)
def RunCommand(cmd, print_cmd=True, error_ok=False, error_message=None, exit_code=False, redirect_stdout=False, redirect_stderr=False, cwd=None, input=None, enter_chroot=False, shell=False): """Runs a command. Args: cmd: cmd to run. Should be input to subprocess.Popen. print_cmd: prints the command before running it. error_ok: does not raise an exception on error. error_message: prints out this message when an error occurrs. exit_code: returns the return code of the shell command. redirect_stdout: returns the stdout. redirect_stderr: holds stderr output until input is communicated. cwd: the working directory to run this cmd. input: input to pipe into this command through stdin. enter_chroot: this command should be run from within the chroot. If set, cwd must point to the scripts directory. shell: If shell is True, the specified command will be executed through the shell. Returns: A CommandResult object. Raises: Exception: Raises generic exception on error with optional error_message. """ # Set default for variables. stdout = None stderr = None stdin = None cmd_result = CommandResult() # Modify defaults based on parameters. if redirect_stdout: stdout = subprocess.PIPE if redirect_stderr: stderr = subprocess.PIPE # TODO(sosa): gpylint complains about redefining built-in 'input'. # Can we rename this variable? if input: stdin = subprocess.PIPE if isinstance(cmd, basestring): if enter_chroot: cmd = './enter_chroot.sh -- ' + cmd cmd_str = cmd else: if enter_chroot: cmd = ['./enter_chroot.sh', '--'] + cmd cmd_str = ' '.join(cmd) # Print out the command before running. if print_cmd: Info('RunCommand: %s' % cmd_str) cmd_result.cmd = cmd_str try: proc = subprocess.Popen(cmd_str, cwd=cwd, stdin=stdin, stdout=stdout, stderr=stderr, shell=shell) (cmd_result.output, cmd_result.error) = proc.communicate(input) if exit_code: cmd_result.returncode = proc.returncode if not error_ok and proc.returncode: msg = ('Command "%s" failed.\n' % cmd_str + (error_message or cmd_result.error or cmd_result.output or '')) raise RunCommandError(msg) # TODO(sosa): is it possible not to use the catch-all Exception here? except Exception, e: if not error_ok: raise else: Warning(str(e)) return cmd_result
cwd=None, input=None, enter_chroot=False): """Runs a shell command.
cwd=None, input=None, enter_chroot=False, shell=False): """Runs a command.
def RunCommand(cmd, print_cmd=True, error_ok=False, error_message=None, exit_code=False, redirect_stdout=False, redirect_stderr=False, cwd=None, input=None, enter_chroot=False): """Runs a shell command. Keyword arguments: cmd - cmd to run. Should be input to subprocess.POpen. If a string, converted to an array using split(). print_cmd -- prints the command before running it. error_ok -- does not raise an exception on error. error_message -- prints out this message when an error occurrs. exit_code -- returns the return code of the shell command. redirect_stdout -- returns the stdout. redirect_stderr -- holds stderr output until input is communicated. cwd -- the working directory to run this cmd. input -- input to pipe into this command through stdin. enter_chroot -- this command should be run from within the chroot. If set, cwd must point to the scripts directory. Raises: Exception: Raises generic exception on error with optional error_message. """ # Set default for variables. stdout = None stderr = None stdin = None output = '' # Modify defaults based on parameters. if redirect_stdout: stdout = subprocess.PIPE if redirect_stderr: stderr = subprocess.PIPE if input: stdin = subprocess.PIPE if enter_chroot: cmd = ['./enter_chroot.sh', '--'] + cmd # Print out the command before running. if print_cmd: Info('RunCommand: %s' % ' '.join(cmd)) try: proc = subprocess.Popen(cmd, cwd=cwd, stdin=stdin, stdout=stdout, stderr=stderr) (output, error) = proc.communicate(input) if exit_code: return proc.returncode if not error_ok and proc.returncode: raise Exception('Command "%s" failed.\n' % (' '.join(cmd)) + (error_message or error or output or '')) except Exception,e: if not error_ok: raise else: Warning(str(e)) return output
cmd - cmd to run. Should be input to subprocess.POpen. If a string, converted to an array using split().
cmd - cmd to run. Should be input to subprocess.Popen.
def RunCommand(cmd, print_cmd=True, error_ok=False, error_message=None, exit_code=False, redirect_stdout=False, redirect_stderr=False, cwd=None, input=None, enter_chroot=False): """Runs a shell command. Keyword arguments: cmd - cmd to run. Should be input to subprocess.POpen. If a string, converted to an array using split(). print_cmd -- prints the command before running it. error_ok -- does not raise an exception on error. error_message -- prints out this message when an error occurrs. exit_code -- returns the return code of the shell command. redirect_stdout -- returns the stdout. redirect_stderr -- holds stderr output until input is communicated. cwd -- the working directory to run this cmd. input -- input to pipe into this command through stdin. enter_chroot -- this command should be run from within the chroot. If set, cwd must point to the scripts directory. Raises: Exception: Raises generic exception on error with optional error_message. """ # Set default for variables. stdout = None stderr = None stdin = None output = '' # Modify defaults based on parameters. if redirect_stdout: stdout = subprocess.PIPE if redirect_stderr: stderr = subprocess.PIPE if input: stdin = subprocess.PIPE if enter_chroot: cmd = ['./enter_chroot.sh', '--'] + cmd # Print out the command before running. if print_cmd: Info('RunCommand: %s' % ' '.join(cmd)) try: proc = subprocess.Popen(cmd, cwd=cwd, stdin=stdin, stdout=stdout, stderr=stderr) (output, error) = proc.communicate(input) if exit_code: return proc.returncode if not error_ok and proc.returncode: raise Exception('Command "%s" failed.\n' % (' '.join(cmd)) + (error_message or error or output or '')) except Exception,e: if not error_ok: raise else: Warning(str(e)) return output
if enter_chroot: cmd = ['./enter_chroot.sh', '--'] + cmd
if isinstance(cmd, basestring): if enter_chroot: cmd = './enter_chroot.sh -- ' + cmd cmd_str = cmd else: if enter_chroot: cmd = ['./enter_chroot.sh', '--'] + cmd cmd_str = ' '.join(cmd)
def RunCommand(cmd, print_cmd=True, error_ok=False, error_message=None, exit_code=False, redirect_stdout=False, redirect_stderr=False, cwd=None, input=None, enter_chroot=False): """Runs a shell command. Keyword arguments: cmd - cmd to run. Should be input to subprocess.POpen. If a string, converted to an array using split(). print_cmd -- prints the command before running it. error_ok -- does not raise an exception on error. error_message -- prints out this message when an error occurrs. exit_code -- returns the return code of the shell command. redirect_stdout -- returns the stdout. redirect_stderr -- holds stderr output until input is communicated. cwd -- the working directory to run this cmd. input -- input to pipe into this command through stdin. enter_chroot -- this command should be run from within the chroot. If set, cwd must point to the scripts directory. Raises: Exception: Raises generic exception on error with optional error_message. """ # Set default for variables. stdout = None stderr = None stdin = None output = '' # Modify defaults based on parameters. if redirect_stdout: stdout = subprocess.PIPE if redirect_stderr: stderr = subprocess.PIPE if input: stdin = subprocess.PIPE if enter_chroot: cmd = ['./enter_chroot.sh', '--'] + cmd # Print out the command before running. if print_cmd: Info('RunCommand: %s' % ' '.join(cmd)) try: proc = subprocess.Popen(cmd, cwd=cwd, stdin=stdin, stdout=stdout, stderr=stderr) (output, error) = proc.communicate(input) if exit_code: return proc.returncode if not error_ok and proc.returncode: raise Exception('Command "%s" failed.\n' % (' '.join(cmd)) + (error_message or error or output or '')) except Exception,e: if not error_ok: raise else: Warning(str(e)) return output
Info('RunCommand: %s' % ' '.join(cmd))
Info('RunCommand: %s' % cmd_str)
def RunCommand(cmd, print_cmd=True, error_ok=False, error_message=None, exit_code=False, redirect_stdout=False, redirect_stderr=False, cwd=None, input=None, enter_chroot=False): """Runs a shell command. Keyword arguments: cmd - cmd to run. Should be input to subprocess.POpen. If a string, converted to an array using split(). print_cmd -- prints the command before running it. error_ok -- does not raise an exception on error. error_message -- prints out this message when an error occurrs. exit_code -- returns the return code of the shell command. redirect_stdout -- returns the stdout. redirect_stderr -- holds stderr output until input is communicated. cwd -- the working directory to run this cmd. input -- input to pipe into this command through stdin. enter_chroot -- this command should be run from within the chroot. If set, cwd must point to the scripts directory. Raises: Exception: Raises generic exception on error with optional error_message. """ # Set default for variables. stdout = None stderr = None stdin = None output = '' # Modify defaults based on parameters. if redirect_stdout: stdout = subprocess.PIPE if redirect_stderr: stderr = subprocess.PIPE if input: stdin = subprocess.PIPE if enter_chroot: cmd = ['./enter_chroot.sh', '--'] + cmd # Print out the command before running. if print_cmd: Info('RunCommand: %s' % ' '.join(cmd)) try: proc = subprocess.Popen(cmd, cwd=cwd, stdin=stdin, stdout=stdout, stderr=stderr) (output, error) = proc.communicate(input) if exit_code: return proc.returncode if not error_ok and proc.returncode: raise Exception('Command "%s" failed.\n' % (' '.join(cmd)) + (error_message or error or output or '')) except Exception,e: if not error_ok: raise else: Warning(str(e)) return output
stdout=stdout, stderr=stderr)
stdout=stdout, stderr=stderr, shell=shell)
def RunCommand(cmd, print_cmd=True, error_ok=False, error_message=None, exit_code=False, redirect_stdout=False, redirect_stderr=False, cwd=None, input=None, enter_chroot=False): """Runs a shell command. Keyword arguments: cmd - cmd to run. Should be input to subprocess.POpen. If a string, converted to an array using split(). print_cmd -- prints the command before running it. error_ok -- does not raise an exception on error. error_message -- prints out this message when an error occurrs. exit_code -- returns the return code of the shell command. redirect_stdout -- returns the stdout. redirect_stderr -- holds stderr output until input is communicated. cwd -- the working directory to run this cmd. input -- input to pipe into this command through stdin. enter_chroot -- this command should be run from within the chroot. If set, cwd must point to the scripts directory. Raises: Exception: Raises generic exception on error with optional error_message. """ # Set default for variables. stdout = None stderr = None stdin = None output = '' # Modify defaults based on parameters. if redirect_stdout: stdout = subprocess.PIPE if redirect_stderr: stderr = subprocess.PIPE if input: stdin = subprocess.PIPE if enter_chroot: cmd = ['./enter_chroot.sh', '--'] + cmd # Print out the command before running. if print_cmd: Info('RunCommand: %s' % ' '.join(cmd)) try: proc = subprocess.Popen(cmd, cwd=cwd, stdin=stdin, stdout=stdout, stderr=stderr) (output, error) = proc.communicate(input) if exit_code: return proc.returncode if not error_ok and proc.returncode: raise Exception('Command "%s" failed.\n' % (' '.join(cmd)) + (error_message or error or output or '')) except Exception,e: if not error_ok: raise else: Warning(str(e)) return output
raise Exception('Command "%s" failed.\n' % (' '.join(cmd)) +
raise Exception('Command "%s" failed.\n' % cmd_str +
def RunCommand(cmd, print_cmd=True, error_ok=False, error_message=None, exit_code=False, redirect_stdout=False, redirect_stderr=False, cwd=None, input=None, enter_chroot=False): """Runs a shell command. Keyword arguments: cmd - cmd to run. Should be input to subprocess.POpen. If a string, converted to an array using split(). print_cmd -- prints the command before running it. error_ok -- does not raise an exception on error. error_message -- prints out this message when an error occurrs. exit_code -- returns the return code of the shell command. redirect_stdout -- returns the stdout. redirect_stderr -- holds stderr output until input is communicated. cwd -- the working directory to run this cmd. input -- input to pipe into this command through stdin. enter_chroot -- this command should be run from within the chroot. If set, cwd must point to the scripts directory. Raises: Exception: Raises generic exception on error with optional error_message. """ # Set default for variables. stdout = None stderr = None stdin = None output = '' # Modify defaults based on parameters. if redirect_stdout: stdout = subprocess.PIPE if redirect_stderr: stderr = subprocess.PIPE if input: stdin = subprocess.PIPE if enter_chroot: cmd = ['./enter_chroot.sh', '--'] + cmd # Print out the command before running. if print_cmd: Info('RunCommand: %s' % ' '.join(cmd)) try: proc = subprocess.Popen(cmd, cwd=cwd, stdin=stdin, stdout=stdout, stderr=stderr) (output, error) = proc.communicate(input) if exit_code: return proc.returncode if not error_ok and proc.returncode: raise Exception('Command "%s" failed.\n' % (' '.join(cmd)) + (error_message or error or output or '')) except Exception,e: if not error_ok: raise else: Warning(str(e)) return output
folder_size = 0 for (path, dirs, files) in os.walk(ENV['NODE_PROJECT']): for file in files: filename = os.path.join(path, file) folder_size += os.path.getsize(filename) LOG.info("\t%0.1f MB" % (folder_size/(1024*1024.0)))
LOG.info("\tThis could take a while...") size = sum([os.path.getsize(os.path.join(root,f)) for root,dirs,files in os.walk(ENV['NODE_PROJECT']) for f in files]) LOG.info("\t%0.1f MB" % (size/(1024*1024.0)))
def _cleanup_node_project(): LOG.info("Cleaning up node project: %s" % ENV['NODE_PROJECT']) LOG.info("\tCalculating size...") # pick a folder you have ... folder_size = 0 for (path, dirs, files) in os.walk(ENV['NODE_PROJECT']): for file in files: filename = os.path.join(path, file) folder_size += os.path.getsize(filename) LOG.info("\t%0.1f MB" % (folder_size/(1024*1024.0))) call('rmdir /S /Q %s' % ENV['NODE_PROJECT'], shell=True)
__VERSION_TAG__ = "rc12"
__VERSION_TAG__ = "rc14"
def get_log(name=__name__, stream=False): log = logging.getLogger(name) log.setLevel(__LOG_LEVEL__) if stream: handler = logging.StreamHandler() formatter = logging.Formatter("%(name)s %(levelname)s: %(message)s") handler.setFormatter(formatter) log.addHandler(handler) return log
self.assertRaises(InvalidPathError, ProjectPath, r"Z:\my\path") self.assertRaises(InvalidPathError, ProjectPath, "Z:/my/path")
def test_invalid_path(self): self.assertRaises(InvalidPathError, ProjectPath, r"D:\my\path") self.assertRaises(InvalidPathError, ProjectPath, "D:/my/path") self.assertRaises(InvalidPathError, ProjectPath, r"Z:\my\path") self.assertRaises(InvalidPathError, ProjectPath, "Z:/my/path")
tail = "maya\\foo\\scenes\\bar.mb"
tail = "\\maya\\foo\\scenes\\bar.mb"
def test_nt_letter_unc_substitution(self): tail = "maya\\foo\\scenes\\bar.mb" self.assertEquals(ProjectPath(SPOOL_LETTER, tail).path, ProjectPath(SPOOL_UNC, tail).path) self.assertEquals(ProjectPath(SPOOL_LETTER, tail).unc, ProjectPath(SPOOL_UNC, tail).unc) self.assertEquals(ProjectPath(SPOOL_LETTER, tail).ppath, ProjectPath(SPOOL_UNC, tail).ppath) self.assertEquals(ProjectPath(SPOOL_LETTER, tail).punc, ProjectPath(SPOOL_UNC, tail).punc)
'scene' : str(self.scene_field.currentText()),
'scene' : os.path.basename(str(self.scene_field.currentText())),
def job_data(self): job_uuid = JobSpec.new_uuid() start_frame = min((int(self.start_field.value()), int(self.end_field.value()))) end_frame = max((int(self.start_field.value()), int(self.end_field.value()))) image_filename = str(self.output_base_field.text()) + str(self.output_ext_field.currentText()) return { 'renderer' : 'max', 'title' : str(self.title_field.text()), 'uuid' : job_uuid, 'project' : os.path.normpath(str(self.project_field.text())), 'scene' : str(self.scene_field.currentText()), 'output' : os.path.join(JOB_OUTPUT_UNC, getpass.getuser(), job_uuid, image_filename), 'start' : start_frame, 'end' : end_frame, 'step' : str(self.step_field.value()), 'threads' : 0 }
print self.data
def __init__(self, title, project, scene, start, end, step=1, **kwargs): data = dict(title=title, project=project, scene=scene, start=start, end=end, step=step) data.update(kwargs) self._set_data(data) print self.data
spec.submit_job(pause=True if os.environ['RRT_DEBUG'] else False)
spec.submit_job(pause=True if os.getenv('RRT_DEBUG', False) else False)
def submit_job(self): try: spec = JobSpec(**self.job_data) # TODO: find a better place to do this. if not str(self.output_base_field.text()): raise RuntimeError("Output cannot be blank.") # Key env vars that influence submission os.environ['HEAD_NODE'] = str(self.head_node_field.currentText()) spec.submit_job(pause=True if os.environ['RRT_DEBUG'] else False) self.quit() except Exception, e: alert = QtGui.QMessageBox(self) alert.setWindowTitle('Error') alert.setIcon(QtGui.QMessageBox.Warning) alert.setText(str(e)) alert.exec_()
LOG.info("Connecting to cluster at: %s" % self.HeadNode)
def DoIt(self): scheduler = Scheduler() # make a connection to the cluster LOG.info("Connecting to cluster at: %s" % self.HeadNode) try: scheduler.Connect(self.HeadNode) except Exception, e: LOG.error("Unable to reach cluster head node: %s" % self.HeadNode) LOG.error(e) LOG.info("Exiting...") sys.exit(2)
scheduler.Connect(self.HeadNode)
LOG.info("Connecting to cluster at: %s" % self.HeadNode) try: scheduler.Connect(self.HeadNode) except Exception, e: LOG.error("Unable to reach cluster head node: %s" % self.HeadNode) LOG.error(e) LOG.info("Exiting...") sys.exit(2) job = scheduler.CreateJob() job.Name = self._conf["name"] job.IsExclusive = True self.BuildTaskList(job) scheduler.SubmitJob(job, self.RUNAS_USER, self.RUNAS_PASSWORD) LOG.info("Submitted job %d to %s." % (job.Id, self.HeadNode)) scheduler.Close()
def DoIt(self): scheduler = Scheduler() # make a connection to the cluster LOG.info("Connecting to cluster at: %s" % self.HeadNode) try: scheduler.Connect(self.HeadNode) except Exception, e: LOG.error("Unable to reach cluster head node: %s" % self.HeadNode) LOG.error(e) LOG.info("Exiting...") sys.exit(2)
LOG.error("Unable to reach cluster head node: %s" % self.HeadNode)
def DoIt(self): scheduler = Scheduler() # make a connection to the cluster LOG.info("Connecting to cluster at: %s" % self.HeadNode) try: scheduler.Connect(self.HeadNode) except Exception, e: LOG.error("Unable to reach cluster head node: %s" % self.HeadNode) LOG.error(e) LOG.info("Exiting...") sys.exit(2)
LOG.info("Exiting...") sys.exit(2) job = scheduler.CreateJob() job.Name = self._conf["name"] job.IsExclusive = True self.BuildTaskList(job) scheduler.SubmitJob(job, self.RUNAS_USER, self.RUNAS_PASSWORD) LOG.info("Submitted job %d to %s." % (job.Id, self.HeadNode))
finally: scheduler.Dispose()
def DoIt(self): scheduler = Scheduler() # make a connection to the cluster LOG.info("Connecting to cluster at: %s" % self.HeadNode) try: scheduler.Connect(self.HeadNode) except Exception, e: LOG.error("Unable to reach cluster head node: %s" % self.HeadNode) LOG.error(e) LOG.info("Exiting...") sys.exit(2)
print >> sys.stderr, "\nError!" print >> sys.stderr, "HEAD_NODE is null - please set HEAD_NODE." print >> sys.stderr, "Exiting..."
LOG.error("HEAD_NODE is null - please set HEAD_NODE.") LOG.info("Exiting...")
def HeadNode(self): host = os.getenv("HEAD_NODE", None) if None == host: print >> sys.stderr, "\nError!" print >> sys.stderr, "HEAD_NODE is null - please set HEAD_NODE." print >> sys.stderr, "Exiting..." sys.exit(1) return host.strip()
task.SetEnvironmentVariable("TEMP", self._conf["user_dir"]) task.SetEnvironmentVariable("TMP", self._conf["user_dir"])
task.SetEnvironmentVariable("TEMP", self._conf["node_project"]) task.SetEnvironmentVariable("TMP", self._conf["node_project"])
def SetJobEnv(self,task): task.SetEnvironmentVariable("MAYA_APP_DIR", self._conf["user_dir"]) task.SetEnvironmentVariable("TEMP", self._conf["user_dir"]) task.SetEnvironmentVariable("TMP", self._conf["user_dir"]) task.SetEnvironmentVariable("OWNER", getpass.getuser()) task.SetEnvironmentVariable("USER_DIR", self._conf["user_dir"]) task.SetEnvironmentVariable("NODE_PROJECT", self._conf["node_project"]) # self override enables us to apply per-job dirmaps on maya jobs task.SetEnvironmentVariable("MAYA_SCRIPT_PATH", self._conf["node_project"]+ r"\scripts;"+os.getenv("MAYA_SCRIPT_PATH", '')) task.SetEnvironmentVariable("PROJECT", self._conf["project"]) task.SetEnvironmentVariable("SCENE", self._conf["scene"]) task.SetEnvironmentVariable("RENDERER", self._conf["renderer"]) task.SetEnvironmentVariable("LOGS", self._conf["logs"]) task.SetEnvironmentVariable("OUTPUT", self._conf["output"])
print "Connecting to cluster at: %s" % self.HeadNode
LOG.info("Connecting to cluster at: %s" % self.HeadNode)
def DoIt(self): scheduler = Scheduler() # make a connection to the cluster print "Connecting to cluster at: %s" % self.HeadNode try: scheduler.Connect(self.HeadNode) except: print >> sys.stderr, "\nError!" print >> sys.stderr, "Unable to reach cluster head node: %s" % self.HeadNode print >> sys.stderr, "Exiting..." sys.exit(2)
except: print >> sys.stderr, "\nError!" print >> sys.stderr, "Unable to reach cluster head node: %s" % self.HeadNode print >> sys.stderr, "Exiting..."
except Exception, e: LOG.error("Unable to reach cluster head node: %s" % self.HeadNode) LOG.error(e) LOG.info("Exiting...")
def DoIt(self): scheduler = Scheduler() # make a connection to the cluster print "Connecting to cluster at: %s" % self.HeadNode try: scheduler.Connect(self.HeadNode) except: print >> sys.stderr, "\nError!" print >> sys.stderr, "Unable to reach cluster head node: %s" % self.HeadNode print >> sys.stderr, "Exiting..." sys.exit(2)
self.BuildTaskList(job) scheduler.SubmitJob(job, self.RUNAS_USER, self.RUNAS_PASSWORD) print "Submitted job %d to %s." % (job.Id, self.HeadNode)
self.BuildTaskList(job) scheduler.SubmitJob(job, self.RUNAS_USER, self.RUNAS_PASSWORD) LOG.info("Submitted job %d to %s." % (job.Id, self.HeadNode))
def DoIt(self): scheduler = Scheduler() # make a connection to the cluster print "Connecting to cluster at: %s" % self.HeadNode try: scheduler.Connect(self.HeadNode) except: print >> sys.stderr, "\nError!" print >> sys.stderr, "Unable to reach cluster head node: %s" % self.HeadNode print >> sys.stderr, "Exiting..." sys.exit(2)
print >> sys.stderr, "\nError!" print >> sys.stderr, "Must specify an ini file." print >> sys.stderr, "Exiting..."
LOG.error("Must specify an ini file.") LOG.info("Exiting...")
def main(): conf_path = None try: conf_path = os.path.abspath(sys.argv[1]) except IndexError: print >> sys.stderr, "\nError!" print >> sys.stderr, "Must specify an ini file." print >> sys.stderr, "Exiting..." sys.exit(3) print "Spooling job from %s" % conf_path try: spool = Spooler(conf_path) spool.DoIt() except Exception, e: print >> sys.stderr, e sys.exit(-1)
print "Spooling job from %s" % conf_path
LOG.info("Spooling job from %s" % conf_path)
def main(): conf_path = None try: conf_path = os.path.abspath(sys.argv[1]) except IndexError: print >> sys.stderr, "\nError!" print >> sys.stderr, "Must specify an ini file." print >> sys.stderr, "Exiting..." sys.exit(3) print "Spooling job from %s" % conf_path try: spool = Spooler(conf_path) spool.DoIt() except Exception, e: print >> sys.stderr, e sys.exit(-1)
print >> sys.stderr, e
LOG.error(e)
def main(): conf_path = None try: conf_path = os.path.abspath(sys.argv[1]) except IndexError: print >> sys.stderr, "\nError!" print >> sys.stderr, "Must specify an ini file." print >> sys.stderr, "Exiting..." sys.exit(3) print "Spooling job from %s" % conf_path try: spool = Spooler(conf_path) spool.DoIt() except Exception, e: print >> sys.stderr, e sys.exit(-1)
except OSError: self.infostring = BAD_INFO self.accessible = False
def determine_infostring(self): self.size = 0 if self.is_device: self.infostring = 'dev' elif self.is_fifo: self.infostring = 'fifo' elif self.is_socket: self.infostring = 'sock' elif self.is_directory: try: self.size = len(os.listdir(self.path)) self.infostring = " %d" % self.size self.accessible = True self.runnable = True except OSError: self.infostring = BAD_INFO self.accessible = False elif self.is_file: self.size = self.stat.st_size self.infostring = ' ' + human_readable(self.size) if self.is_link: self.infostring = '->'
self.size = self.stat.st_size self.infostring = ' ' + human_readable(self.size)
try: self.size = self.stat.st_size self.infostring = ' ' + human_readable(self.size) except: pass
def determine_infostring(self): self.size = 0 if self.is_device: self.infostring = 'dev' elif self.is_fifo: self.infostring = 'fifo' elif self.is_socket: self.infostring = 'sock' elif self.is_directory: try: self.size = len(os.listdir(self.path)) self.infostring = " %d" % self.size self.accessible = True self.runnable = True except OSError: self.infostring = BAD_INFO self.accessible = False elif self.is_file: self.size = self.stat.st_size self.infostring = ' ' + human_readable(self.size) if self.is_link: self.infostring = '->'
self.infostring = '->'
self.infostring = '->' + self.infostring
def determine_infostring(self): self.size = 0 if self.is_device: self.infostring = 'dev' elif self.is_fifo: self.infostring = 'fifo' elif self.is_socket: self.infostring = 'sock' elif self.is_directory: try: self.size = len(os.listdir(self.path)) self.infostring = " %d" % self.size self.accessible = True self.runnable = True except OSError: self.infostring = BAD_INFO self.accessible = False elif self.is_file: self.size = self.stat.st_size self.infostring = ' ' + human_readable(self.size) if self.is_link: self.infostring = '->'
if target is None \ or not target.accessible \ or (target.is_directory and target.files is None):
if target is None or not target.accessible:
def _get_left_part(self, bar): left = bar.left
if target is None: return
def _get_right_part(self, bar): right = bar.right if self.column is None: return
if self.settings.flushinput: curses.flushinp()
def handle_input(self): key = self.win.getch() if key is 27 or key >= 128 and key < 256: # Handle special keys like ALT+X or unicode here: keys = [key] previous_load_mode = self.load_mode self.set_load_mode(True) for n in range(4): getkey = self.win.getch() if getkey is not -1: keys.append(getkey) if len(keys) == 1: keys.append(-1) if self.settings.xterm_alt_key: if len(keys) == 2 and keys[1] in range(127, 256): keys = [27, keys[1] - 128] self.handle_keys(*keys) self.set_load_mode(previous_load_mode) if self.settings.flushinput: curses.flushinp() else: # Handle simple key presses, CTRL+X, etc here: if self.settings.flushinput: curses.flushinp() if key > 0: if key == curses.KEY_MOUSE: self.handle_mouse() elif key == curses.KEY_RESIZE: self.update_size() else: if not self.fm.input_is_blocked(): self.handle_key(key)
map('gn', fm.cd('/mnt'))
map('gM', fm.cd('/mnt'))
def insert_before_filename(arg): append_to_filename(arg) arg.fm.ui.console.move(right=len('rename '), absolute=True)
try: handlers = self._signals[signal_name] except: return
if signal_name not in self._signals: return True handlers = self._signals[signal_name]
def signal_emit(self, signal_name, **kw): assert isinstance(signal_name, str) try: handlers = self._signals[signal_name] except: return if not handlers: return
return
return True
def signal_emit(self, signal_name, **kw): assert isinstance(signal_name, str) try: handlers = self._signals[signal_name] except: return if not handlers: return
return
return False
def signal_emit(self, signal_name, **kw): assert isinstance(signal_name, str) try: handlers = self._signals[signal_name] except: return if not handlers: return
macros[i + 'f'] = shell_quote(tab_dir.pointed_obj.path)
if tab_dir.pointed_obj: macros[i + 'f'] = shell_quote(tab_dir.pointed_obj.path)
def _substitute_metachars(self, command): macros = {}
macros['F'] = shell_quote(next_tab.pointed_obj.path)
if next_tab.pointed_obj: macros['F'] = shell_quote(next_tab.pointed_obj.path)
def _substitute_metachars(self, command): macros = {}
self.env.signal_bind('cd', self._update_current_tab)
def __init__(self, ui=None, bookmarks=None, tags=None): """Initialize FM.""" Actions.__init__(self) SignalDispatcher.__init__(self) self.ui = ui self.log = deque(maxlen=20) self.bookmarks = bookmarks self.tags = tags self.tabs = {} self.current_tab = 1 self.loader = Loader() self._executables = None self.apps = self.settings.apps.CustomApplications()
self.type_key(chrkey) self.env.key_clear() return
def press(self, key): from curses.ascii import ctrl, ESC
self.env.copy -= selected
self.env.copy -= set(selected)
def delete(self): self.notify("Deleting!", duration=1) selected = self.env.get_selection() self.env.copy -= selected if selected: for f in selected: if os.path.isdir(f.path) and not os.path.islink(f.path): try: shutil.rmtree(f.path) except OSError as err: self.notify(str(err), bad=True) else: try: os.remove(f.path) except OSError as err: self.notify(str(err), bad=True)
crash_exception = None
crash_traceback = None
def print_function(string): print(string)
crash_exception = e if not (arg.debug or arg.clean): import traceback dumpname = ranger.relpath_conf('traceback') traceback.print_exc(file=open(dumpname, 'w'))
import traceback crash_traceback = traceback.format_exc()
def print_function(string): print(string)
if crash_exception: print("Fatal: " + str(crash_exception)) if arg.debug or arg.clean: raise crash_exception else: print("A traceback has been saved to " + dumpname) print("Please include it in a bugreport.")
if crash_traceback: print(crash_traceback) print("Ranger crashed. " \ "Please report it (including the traceback) at:") print("http://savannah.nongnu.org/bugs/?group=ranger&func=additem")
def print_function(string): print(string)
cp_flags = ['--backup=numbered', '-af', '--'] mv_flags = ['--backup=numbered', '-f', '--']
cp_flags = ['-af', '--'] mv_flags = ['-f', '--']
def refresh(_): cwd = self.env.get_directory(original_path) cwd.load_content()
_, dirnames, _ = os.walk(abs_dest).next()
_, dirnames, _ = next(os.walk(abs_dest))
def _tab_only_directories(self): from os.path import dirname, basename, expanduser, join, isdir
_, dirnames, _ = os.walk(abs_dirname).next()
_, dirnames, _ = next(os.walk(abs_dirname))
def _tab_only_directories(self): from os.path import dirname, basename, expanduser, join, isdir
_, dirnames, filenames = os.walk(abs_dest).next()
_, dirnames, filenames = next(os.walk(abs_dest))
def _tab_directory_content(self): from os.path import dirname, basename, expanduser, join, isdir
_, dirnames, filenames = os.walk(abs_dirname).next()
_, dirnames, filenames = next(os.walk(abs_dirname))
def _tab_directory_content(self): from os.path import dirname, basename, expanduser, join, isdir
if self.target.is_directory \ and self.target.pointed_obj != self.old_cf: self.need_redraw = True self.old_cf = self.target.pointed_obj if self.target.is_directory: if self.target.load_content_if_outdated():
if self.target and self.target.is_directory: if self.target.pointed_obj != self.old_cf:
def draw(self): """Call either _draw_file() or _draw_directory()""" from ranger import log
elif self.target.sort_if_outdated(): self.need_redraw = True elif self.last_redraw_time < self.target.last_update_time:
self.old_cf = self.target.pointed_obj if self.target.load_content_if_outdated() \ or self.target.sort_if_outdated() \ or self.last_redraw_time < self.target.last_update_time:
def draw(self): """Call either _draw_file() or _draw_directory()""" from ranger import log
if x > self.x:
if x > 0:
def _draw_directory(self): """Draw the contents of a directory"""
import ranger
import ranger.shared
def load_settings(fm, clean): import ranger import ranger.api.commands if not clean: allow_access_to_confdir(ranger.arg.confdir, True) # Load commands comcont = ranger.api.commands.CommandContainer() ranger.api.commands.alias = comcont.alias try: import commands comcont.load_commands_from_module(commands) except ImportError: pass from ranger.defaults import commands comcont.load_commands_from_module(commands) commands = comcont # Load apps try: import apps except ImportError: from ranger.defaults import apps # Load keys from ranger import shared, api from ranger.api import keys keymanager = shared.EnvironmentAware.env.keymanager keys.keymanager = keymanager from ranger.defaults import keys try: import keys except ImportError: pass # COMPAT WARNING if hasattr(keys, 'initialize_commands'): print("Warning: the syntax for ~/.ranger/keys.py has changed.") print("Your custom keys are not loaded."\ " Please update your configuration.") allow_access_to_confdir(ranger.arg.confdir, False) else: comcont = ranger.api.commands.CommandContainer() ranger.api.commands.alias = comcont.alias from ranger.defaults import commands, keys, apps comcont.load_commands_from_module(commands) commands = comcont fm.commands = commands fm.keys = keys fm.apps = apps.CustomApplications()
from ranger import shared, api from ranger.api import keys keymanager = shared.EnvironmentAware.env.keymanager keys.keymanager = keymanager
keymanager = ranger.shared.EnvironmentAware.env.keymanager ranger.api.keys.keymanager = keymanager
def load_settings(fm, clean): import ranger import ranger.api.commands if not clean: allow_access_to_confdir(ranger.arg.confdir, True) # Load commands comcont = ranger.api.commands.CommandContainer() ranger.api.commands.alias = comcont.alias try: import commands comcont.load_commands_from_module(commands) except ImportError: pass from ranger.defaults import commands comcont.load_commands_from_module(commands) commands = comcont # Load apps try: import apps except ImportError: from ranger.defaults import apps # Load keys from ranger import shared, api from ranger.api import keys keymanager = shared.EnvironmentAware.env.keymanager keys.keymanager = keymanager from ranger.defaults import keys try: import keys except ImportError: pass # COMPAT WARNING if hasattr(keys, 'initialize_commands'): print("Warning: the syntax for ~/.ranger/keys.py has changed.") print("Your custom keys are not loaded."\ " Please update your configuration.") allow_access_to_confdir(ranger.arg.confdir, False) else: comcont = ranger.api.commands.CommandContainer() ranger.api.commands.alias = comcont.alias from ranger.defaults import commands, keys, apps comcont.load_commands_from_module(commands) commands = comcont fm.commands = commands fm.keys = keys fm.apps = apps.CustomApplications()
map('c', hint='//c//time //m//imetype //s//ize')
map('c', hint='//c//time //m//imetype //s//ize //t//agged')
def append_to_filename(arg): command = 'rename ' + arg.fm.env.cf.basename arg.fm.open_console(cmode.COMMAND, command)
sys.exit(1 if arg.fail_unless_cd else 0)
return 1 if arg.fail_unless_cd else 0
def print_function(string): print(string)
import os signal.value = os.path.expanduser(signal.value)
if isinstance(signal.value, str): import os signal.value = os.path.expanduser(signal.value)
def postprocess_paths(signal): import os signal.value = os.path.expanduser(signal.value)
try: destination = line.rest(1) except IndexError:
destination = line.rest(1) if not destination:
def execute(self): line = parse(self.line) try: destination = line.rest(1) except IndexError: destination = '~'
elif hasattr(self, 'prompt'):
elif 'prompt' in self.__dict__:
def open(self, mode, string='', prompt=None): if not is_valid_mode(mode): return False if prompt is not None: assert isinstance(prompt, str) self.prompt = prompt elif hasattr(self, 'prompt'): del self.prompt
"Please report this (including the traceback) at:")
"Please report this traceback at:")
def print_function(string): print(string)
self.addstr(self.line)
overflow = -self.wid + len(self.prompt) + len(self.line) + 1 if overflow > 0: self.addstr(self.line[overflow:]) else: self.addstr(self.line)
def draw(self): if self.mode is None: return
self.x + self.pos + len(self.prompt))
self.x + min(self.wid-1, self.pos + len(self.prompt)))
def finalize(self): try: self.fm.ui.win.move(self.y, self.x + self.pos + len(self.prompt)) except: pass
try: rel_dest = line.rest(1) except IndexError:
rel_dest = line.rest(1) if not rel_dest:
def quick_open(self): from os.path import isdir, join, normpath line = parse(self.line) pwd = self.fm.env.pwd.path
oversize = leftsize + rightsize - wid
oversize = leftsize + rightsize - wid - 1
def shrink_from_the_left(self, wid): fixedsize = self.fixedsize() if wid < fixedsize: raise ValueError("Cannot shrink down to that size by cutting") leftsize = self.left.sumsize() rightsize = self.right.sumsize() oversize = leftsize + rightsize - wid if oversize <= 0: return self.fill_gap(' ', wid, gapwidth=False) nonfixed_items = self.left.nonfixed_items()
filename = fsobj.basename_lower
if case_insensitive: filename = fsobj.basename_lower else: filename = fsobj.basename
def _search(self): self.count = 0 line = parse(self.line) cwd = self.fm.env.cwd try: arg = line.rest(1) except IndexError: return False
pager.set_source(lines)
def display_help(self, topic='index', narg=None): if not hasattr(self.ui, 'open_pager'): return
if cmd.startswith(name) \ and cls.allow_abbrev \
if cls.allow_abbrev and cmd.startswith(name) \
def get_command(self, name, abbrev=True): if abbrev: lst = [cls for cmd, cls in self.commands.items() \ if cmd.startswith(name) \ and cls.allow_abbrev \ or cmd == name] if len(lst) == 0: raise KeyError if len(lst) == 1 or self.commands[name] in lst: return lst[0] raise ValueError("Ambiguous command") else: try: return self.commands[name] except KeyError: return None
if len(lst) == 1 or self.commands[name] in lst:
if len(lst) == 1:
def get_command(self, name, abbrev=True): if abbrev: lst = [cls for cmd, cls in self.commands.items() \ if cmd.startswith(name) \ and cls.allow_abbrev \ or cmd == name] if len(lst) == 0: raise KeyError if len(lst) == 1 or self.commands[name] in lst: return lst[0] raise ValueError("Ambiguous command") else: try: return self.commands[name] except KeyError: return None
or self.columns[-1].has_preview():
or self.columns[-1].has_preview() and not self.pager.visible:
def poke(self): DisplayableContainer.poke(self)
self.load_content_mtime = os.lstat(self.path).st_mtime
self.load_content_mtime = os.stat(self.path).st_mtime
def load_bit_by_bit(self): """ Returns a generator which load a part of the directory in each iteration. """
real_mtime = os.lstat(self.path).st_mtime
real_mtime = os.stat(self.path).st_mtime
def load_content_if_outdated(self, *a, **k): """ Load the contents of the directory if it's outdated or not done yet """
from collections import deque directory = self.fm.env.get_directory(c.file.dirname) images = [f.path for f in directory.files if f.image] position = images.index(c.file.path) deq = deque(images) deq.rotate(-position) return tup('feh', *deq)
try: from collections import deque directory = self.fm.env.get_directory(c.file.dirname) images = [f.path for f in directory.files if f.image] position = images.index(c.file.path) deq = deque(images) deq.rotate(-position) return tup('feh', *deq) except: return tup('feh', *c)
def app_feh(self, c): arg = {1: '--bg-scale', 2: '--bg-tile', 3: '--bg-center'}
ctime = self.env.cf.stat.st_ctime
try: ctime = self.env.cf.stat.st_ctime except: ctime = -1
def draw(self): """Draw the statusbar"""
return [int(c) if c.isdigit() else c \
return [int(c) if c.isdigit() else c or 0 \
def basename_natural(self): return [int(c) if c.isdigit() else c \ for c in _extract_number_re.split(self.basename)]
return [int(c) if c.isdigit() else c \
return [int(c) if c.isdigit() else c or 0 \
def basename_natural_lower(self): return [int(c) if c.isdigit() else c \ for c in _extract_number_re.split(self.basename_lower)]
if not overwrite and os.path.isdir(dst): real_dst = os.path.join(dst, _basename(src)) if os.path.exists(real_dst): raise Error("Destination path '%s' already exists" % real_dst)
def move(src, dst, overwrite=False): """Recursively move a file or directory to another location. This is similar to the Unix "mv" command. If the destination is a directory or a symlink to a directory, the source is moved inside the directory. The destination path must not already exist. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics. If the destination is on our current filesystem, then rename() is used. Otherwise, src is copied to the destination and then removed. A lot more could be done here... A look at a mv.c shows a lot of the issues this implementation glosses over. """ real_dst = dst if not overwrite and os.path.isdir(dst): real_dst = os.path.join(dst, _basename(src)) if os.path.exists(real_dst): raise Error("Destination path '%s' already exists" % real_dst) if not overwrite: real_dst = get_safe_path(real_dst) try: os.rename(src, real_dst) except OSError: if os.path.isdir(src): if _destinsrc(src, dst): raise Error("Cannot move a directory '%s' into itself '%s'." % (src, dst)) for _ in copytree(src, real_dst, symlinks=True, overwrite=overwrite): yield rmtree(src) else: for _ in copy2(src, real_dst, symlinks=True, overwrite=overwrite): yield os.unlink(src)
real_dst = get_safe_path(real_dst)
real_dst = get_safe_path(os.path.join(dst, _basename(src)))
def move(src, dst, overwrite=False): """Recursively move a file or directory to another location. This is similar to the Unix "mv" command. If the destination is a directory or a symlink to a directory, the source is moved inside the directory. The destination path must not already exist. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics. If the destination is on our current filesystem, then rename() is used. Otherwise, src is copied to the destination and then removed. A lot more could be done here... A look at a mv.c shows a lot of the issues this implementation glosses over. """ real_dst = dst if not overwrite and os.path.isdir(dst): real_dst = os.path.join(dst, _basename(src)) if os.path.exists(real_dst): raise Error("Destination path '%s' already exists" % real_dst) if not overwrite: real_dst = get_safe_path(real_dst) try: os.rename(src, real_dst) except OSError: if os.path.isdir(src): if _destinsrc(src, dst): raise Error("Cannot move a directory '%s' into itself '%s'." % (src, dst)) for _ in copytree(src, real_dst, symlinks=True, overwrite=overwrite): yield rmtree(src) else: for _ in copy2(src, real_dst, symlinks=True, overwrite=overwrite): yield os.unlink(src)
map.dir('%', down=1, percentage=True, absolute=True)
map.dir('%', down=50, percentage=True, absolute=True)
def move(arg): arg.wdg.move(narg=arg.n, **arg.direction)
offset=-self.wid)
offset=-self.wid + 1)
def move(self, narg=None, **kw): direction = Direction(kw) if direction.horizontal(): self.startx = direction.move( direction=direction.right(), override=narg, maximum=self._get_max_width(), current=self.startx, pagesize=self.wid, offset=-self.wid) if direction.vertical(): if self.source_is_stream: self._get_line(self.scroll_begin + self.hei * 2) self.scroll_begin = direction.move( direction=direction.down(), override=narg, maximum=len(self.lines), current=self.scroll_begin, pagesize=self.hei, offset=-self.hei)
offset=-self.hei)
offset=-self.hei + 1)
def move(self, narg=None, **kw): direction = Direction(kw) if direction.horizontal(): self.startx = direction.move( direction=direction.right(), override=narg, maximum=self._get_max_width(), current=self.startx, pagesize=self.wid, offset=-self.wid) if direction.vertical(): if self.source_is_stream: self._get_line(self.scroll_begin + self.hei * 2) self.scroll_begin = direction.move( direction=direction.down(), override=narg, maximum=len(self.lines), current=self.scroll_begin, pagesize=self.hei, offset=-self.hei)
for l in self.source: self.lines.append(l) if len(self.lines) > n: break
try: for l in self.source: self.lines.append(l) if len(self.lines) > n: break except UnicodeError: pass
def _get_line(self, n, attempt_to_read=True): try: return self.lines[n] except (KeyError, IndexError): if attempt_to_read and self.source_is_stream: for l in self.source: self.lines.append(l) if len(self.lines) > n: break return self._get_line(n, attempt_to_read=False) return ""
return tup("zsnes", c.file)
return tup("zsnes", c.file.path)
def app_zsnes(self, c): return tup("zsnes", c.file)
return tup("wine", c.file)
return tup("wine", c.file.path)
def app_wine(self, c): return tup("wine", c.file)
methods = self.__class__.__dict__ return [meth[4:] for meth in methods if meth.startswith('app_')]
result = set() for cls in self.__class__.__mro__: result |= set(m[4:] for m in cls.__dict__ if m.startswith('app_')) return sorted(result)
def all(self): """Returns a list with all application functions""" methods = self.__class__.__dict__ return [meth[4:] for meth in methods if meth.startswith('app_')]
bind('cs', fm.search(order='mimetype'))
bind('cs', fm.search(order='size'))
def edit_name(arg): cf = arg.fm.env.cf if cf: arg.fm.open_console(cmode.COMMAND, 'rename ' + cf.basename)