Python os.path.basename() Examples

The following are code examples for showing how to use os.path.basename(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: cxflow-tensorflow   Author: Cognexa   File: model_test.py    (license) View Source Project 6 votes vote down vote up
def test_keep_checkpoints(self):
        """
        Test if the checkpoints are kept.

        This is regression test for issue #71 (TF ``Saver`` is keeping only the last 5 checkpoints).
        """
        dummy_model = SimpleModel(dataset=None, log_dir=self.tmpdir, inputs=[], outputs=['output'])

        checkpoints = []
        for i in range(20):
            checkpoints.append(dummy_model.save(str(i)))

        for checkpoint in checkpoints:
            self.assertTrue(path.exists(checkpoint+'.index'))
            self.assertTrue(path.exists(checkpoint+'.meta'))
            data_prefix = path.basename(checkpoint)+'.data'
            data_files = [file for file in os.listdir(path.dirname(checkpoint)) if file.startswith(data_prefix)]
            self.assertGreater(len(data_files), 0) 
Example 2
Project: NeoAnalysis   Author: neoanalysis   File: brainwaref32io.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, filename=None):
        '''
        Arguments:
            filename: the filename
        '''
        BaseIO.__init__(self)
        self._path = filename
        self._filename = path.basename(filename)

        self._fsrc = None
        self.__lazy = False

        self._blk = None
        self.__unit = None

        self.__t_stop = None
        self.__params = None
        self.__seg = None
        self.__spiketimes = None 
Example 3
Project: NeoAnalysis   Author: neoanalysis   File: brainwaref32io.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, filename=None):
        '''
        Arguments:
            filename: the filename
        '''
        BaseIO.__init__(self)
        self._path = filename
        self._filename = path.basename(filename)

        self._fsrc = None
        self.__lazy = False

        self._blk = None
        self.__unit = None

        self.__t_stop = None
        self.__params = None
        self.__seg = None
        self.__spiketimes = None 
Example 4
Project: Flask_Blog   Author: sugarguo   File: script.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def print_usage(actions):
    """Print the usage information.  (Help screen)"""
    actions = sorted(iteritems(actions))
    print('usage: %s <action> [<options>]' % basename(sys.argv[0]))
    print('       %s --help' % basename(sys.argv[0]))
    print()
    print('actions:')
    for name, (func, doc, arguments) in actions:
        print('  %s:' % name)
        for line in doc.splitlines():
            print('    %s' % line)
        if arguments:
            print()
        for arg, shortcut, default, argtype in arguments:
            if isinstance(default, bool):
                print('    %s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg
                ))
            else:
                print('    %-30s%-10s%s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg,
                    argtype, default
                ))
        print() 
Example 5
Project: code   Author: ActiveState   File: recipe-576471.py    (MIT License) View Source Project 6 votes vote down vote up
def filter_file(in_file_path, temp_dir_path, filter=None):
    """Runs each line of the file through the given filter.

    The original files is backed up with a "~" added to the end of the file
    name.

    During processing a temporary file, with the same name as as the file to
    process, is created in the given temporary directory.  It only replaces the
    original file if there are no errors.

    """
    temp_file_path = join(temp_dir_path, basename(in_file_path))
    with open(in_file_path, 'r') as in_file:
        with open(temp_file_path, 'w') as temp_file:
            for line in in_file:
                if filter is None or filter(line):
                    temp_file.write(line)
    move(in_file_path, in_file_path + u'~')
    move(temp_file_path, in_file_path) 
Example 6
Project: code   Author: ActiveState   File: recipe-475216.py    (MIT License) View Source Project 6 votes vote down vote up
def parse_sys_argv():
    try:
        # there should be two command line arguments
        assert len(argv) == 3
        # convert <buf_size> and check
        argv[1] = abs(int(argv[1]))
        assert argv[1] > 0
        # convert <run_time> and check
        argv[2] = abs(float(argv[2]))
        assert argv[2] > 0
    except:
        # print out usage information
        print basename(argv[0]),
        print '<buf_size> <run_time>'
        # exits the program
        exit(1)

# called by the producer thread 
Example 7
Project: pineapple   Author: peter765   File: PluginManager.py    (MIT License) View Source Project 6 votes vote down vote up
def register_events(self):
        """
        Request every loaded plugin to present the events they would like to bind to. See util.Events for
        event descriptions
        """
        for name, plugin in self.plugins.items():
            events = plugin.register_events()
            self.comlist[basename(name).lower()] = []
            self.bind_event("Command", self.commands, plugin, events, self.comlist, name)
            self.bind_event("Message", self.message, plugin, events, self.comlist, name)
            self.bind_event("UserJoin", self.join, plugin, events, self.comlist, name)
            self.bind_event("UserLeave", self.leave, plugin, events, self.comlist, name)
            self.bind_event("MessageDelete", self.delete, plugin, events, self.comlist, name)
            self.bind_event("Typing", self.typing, plugin, events, self.comlist, name)
            self.bind_event("Loop", self.loop, plugin, events, self.comlist, name)

    ###
    #   Handling events
    ### 
Example 8
Project: ssbio   Author: SBRG   File: kegg.py    (MIT License) View Source Project 6 votes vote down vote up
def metadata_path(self, m_path):
        """Provide pointers to the paths of the metadata file

        Args:
            m_path: Path to metadata file

        """
        if not m_path:
            self.metadata_dir = None
            self.metadata_file = None

        else:
            if not op.exists(m_path):
                raise OSError('{}: file does not exist!'.format(m_path))

            if not op.dirname(m_path):
                self.metadata_dir = '.'
            else:
                self.metadata_dir = op.dirname(m_path)
            self.metadata_file = op.basename(m_path)

            # TODO: update using Biopython's built in SeqRecord parser
            # Just updating IDs and stuff
            self.update(parse_kegg_gene_metadata(self.metadata_path), overwrite=True) 
Example 9
Project: ssbio   Author: SBRG   File: seqprop.py    (MIT License) View Source Project 6 votes vote down vote up
def feature_path(self, gff_path):
        """Load a GFF file with information on a single sequence and store features in the ``features`` attribute

        Args:
            gff_path: Path to GFF file.

        """
        if not gff_path:
            self.feature_dir = None
            self.feature_file = None

        else:
            if not op.exists(gff_path):
                raise OSError('{}: file does not exist!'.format(gff_path))

            if not op.dirname(gff_path):
                self.feature_dir = '.'
            else:
                self.feature_dir = op.dirname(gff_path)
            self.feature_file = op.basename(gff_path) 
Example 10
Project: ssbio   Author: SBRG   File: dock.py    (MIT License) View Source Project 6 votes vote down vote up
def structure_path(self, path):
        """Provide pointers to the paths of the structure file

        Args:
            path: Path to structure file

        """
        if not path:
            self.structure_dir = None
            self.structure_file = None

        else:
            if not op.exists(path):
                raise OSError('{}: file does not exist!'.format(path))

            if not op.dirname(path):
                self.structure_dir = '.'
            else:
                self.structure_dir = op.dirname(path)
            self.structure_file = op.basename(path) 
Example 11
Project: swjtu-pyscraper   Author: Desgard   File: script.py    (MIT License) View Source Project 6 votes vote down vote up
def print_usage(actions):
    """Print the usage information.  (Help screen)"""
    actions = sorted(iteritems(actions))
    print('usage: %s <action> [<options>]' % basename(sys.argv[0]))
    print('       %s --help' % basename(sys.argv[0]))
    print()
    print('actions:')
    for name, (func, doc, arguments) in actions:
        print('  %s:' % name)
        for line in doc.splitlines():
            print('    %s' % line)
        if arguments:
            print()
        for arg, shortcut, default, argtype in arguments:
            if isinstance(default, bool):
                print('    %s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg
                ))
            else:
                print('    %-30s%-10s%s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg,
                    argtype, default
                ))
        print() 
Example 12
Project: BadParser   Author: stanojevic   File: latexify_results.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def get_sys2results_mapping(dir_with_discodop_files):
    disco_res = glob("%s/*.disco"%dir_with_discodop_files)

    sys_res_map = {}

    for res in disco_res:
        sys_name = basename(res).replace(".disco", "").replace("_", "A").replace("0","zero").replace("1", "one").replace("2", "two").replace("3", "three")
        sys_res_map[sys_name] = {}
        disco_res_values = get_res_from_discodop(res)
        for key, val in disco_res_values.items():
            sys_res_map[sys_name]["d"+key] = val
        all_res_values = get_res_from_discodop(res.replace(".disco", ".all"))
        for key, val in all_res_values.items():
            sys_res_map[sys_name]["a"+key] = val

    return sys_res_map 
Example 13
Project: albt   Author: geothird   File: lamb.py    (license) View Source Project 6 votes vote down vote up
def zip_add_dir(path, zipf, keep_parent=False):
        """
        Add directory to zip file
        :param path:
        :param zipf:
        :param keep_parent:
        :return:
        """
        base = basename(path)
        if keep_parent:
            len_dir_path = len(path)-len(base)
        else:
            len_dir_path = len(path)
        for root, _, files in os.walk(path):
            for f in files:
                file_path = os.path.join(root, f)
                zipf.write(file_path, file_path[len_dir_path:]) 
Example 14
Project: geekcloud   Author: Mr-Linus   File: log_api.py    (GNU General Public License v2.0) View Source Project 6 votes vote down vote up
def renderTemplate(script_path, time_file_path, dimensions=(24, 80), templatename=DEFAULT_TEMPLATE):
    with copen(script_path, encoding='utf-8', errors='replace', newline='\r\n') as scriptf:
    # with open(script_path) as scriptf:
        with open(time_file_path) as timef:
            timing = getTiming(timef)
            json = scriptToJSON(scriptf, timing)

    fsl = FileSystemLoader(dirname(templatename), 'utf-8')
    e = Environment()
    e.loader = fsl

    templatename = basename(templatename)
    rendered = e.get_template(templatename).render(json=json,
                                                   dimensions=dimensions)

    return rendered 
Example 15
Project: SourceFilterContoursMelody   Author: juanjobosch   File: melodyExtractionFromSalienceFunction.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def MEFromFileNumInFolder(salsfolder, outfolder, fileNum, options):
    """ Auxiliar function, to extract melody from a folder with precomputed and saved saliences (*.Msal)
        Parameters
    ----------
    salsfolder: Folder containing saved saliences
    outfolder: melody extraction output folder
    fileNum: number of the file [1:numfiles]
    options: set of options for melody extraction

    No return
    """
    from os.path import join, basename
    import glob

    if not os.path.exists(outfolder):
        os.makedirs(outfolder)

    fn = glob.glob(salsfolder + '*.Msal*')[fileNum - 1]
    bn = basename(fn)
    outputfile = join(outfolder, bn[0:bn.find('.Msal')] + '.pitch')
    MEFromSFFile(fn, outputfile, options) 
Example 16
Project: darkc0de-old-stuff   Author: tuwid   File: create.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def __init__(self, project, arguments=None, stdout="file", stdin=None, timeout=10.0, name=None):
        if not name:
            name = "process:%s" % basename(arguments[0])
        ProjectAgent.__init__(self, project, name)
        self.env = Environment(self)
        if arguments is None:
            arguments = []
        self.cmdline = CommandLine(self, arguments)
        self.timeout = timeout
        self.max_memory = 100*1024*1024
        self.stdout = stdout
        self.popen_args = {
            'stderr': STDOUT,
        }
        if stdin is not None:
            if stdin == "null":
                self.popen_args['stdin'] = open('/dev/null', 'r')
            else:
                raise ValueError("Invalid stdin value: %r" % stdin) 
Example 17
Project: api-manager   Author: edx   File: monitor.py    (GNU Affero General Public License v3.0) View Source Project 6 votes vote down vote up
def create_lambda_function_zip(jinja_env, temp_dir, splunk_host, splunk_token, lf_name):
    """Updates and Zips the lambda function file"""
    splunk_values = {
        'splunk_ip': splunk_host,
        'token': splunk_token,
        'lambda_function_name': lf_name,
    }
    js_file = temp_dir + '/index.js'
    with open(js_file, 'w') as lambda_function_file:
        lf_data = jinja_env.get_template('index.js.j2').render(splunk_values)
        lambda_function_file.write(lf_data)

    zip_file = temp_dir + '/lambda.zip'
    with ZipFile(zip_file, 'w') as lambda_zip:
        lambda_zip.write(js_file, basename(js_file))
    return zip_file 
Example 18
Project: sublime-text-3-packages   Author: nickjj   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def get_formatter_for_filename(fn, **options):
    """Lookup and instantiate a formatter by filename pattern.

    Raises ClassNotFound if not found.
    """
    fn = basename(fn)
    for modname, name, _, filenames, _ in itervalues(FORMATTERS):
        for filename in filenames:
            if _fn_matches(fn, filename):
                if name not in _formatter_cache:
                    _load_formatters(modname)
                return _formatter_cache[name](**options)
    for cls in find_plugin_formatters():
        for filename in cls.filenames:
            if _fn_matches(fn, filename):
                return cls(**options)
    raise ClassNotFound("no formatter found for file name %r" % fn) 
Example 19
Project: sublime-text-3-packages   Author: nickjj   File: st_color_scheme_matcher.py    (MIT License) View Source Project 6 votes vote down vote up
def __init__(self, scheme_file, color_filter=None):
        """Initialize."""
        if color_filter is None:
            color_filter = self.filter
        self.color_scheme = path.normpath(scheme_file)
        self.scheme_file = path.basename(self.color_scheme)
        self.plist_file = color_filter(
            readPlistFromBytes(
                re.sub(
                    br"^[\r\n\s]*<!--[\s\S]*?-->[\s\r\n]*|<!--[\s\S]*?-->", b'',
                    sublime.load_binary_resource(sublime_format_path(self.color_scheme))
                )
            )
        )
        self.scheme_file = scheme_file
        self.matched = {}

        self.parse_scheme() 
Example 20
Project: sublime-text-3-packages   Author: nickjj   File: WordCount.py    (MIT License) View Source Project 6 votes vote down vote up
def should_run_with_syntax(self, view):
		vs =  view.settings()

		syntax = vs.get('syntax')
		syntax = basename(syntax).split('.')[0].lower() if syntax != None else "plain text"

		ws = vs.get('WordCount', wsd)
		ws['syntax'] = syntax
		vs.set('WordCount', ws)

		if len(Pref.blacklist) > 0:
			for white in Pref.blacklist:
				if white == syntax:
					view.erase_status('WordCount');
					return False
		if len(Pref.whitelist) > 0:
			for white in Pref.whitelist:
				if white == syntax:
					return True
			view.erase_status('WordCount');
			return False
		return True 
Example 21
Project: zanph   Author: zanph   File: script.py    (license) View Source Project 6 votes vote down vote up
def print_usage(actions):
    """Print the usage information.  (Help screen)"""
    actions = sorted(iteritems(actions))
    print('usage: %s <action> [<options>]' % basename(sys.argv[0]))
    print('       %s --help' % basename(sys.argv[0]))
    print()
    print('actions:')
    for name, (func, doc, arguments) in actions:
        print('  %s:' % name)
        for line in doc.splitlines():
            print('    %s' % line)
        if arguments:
            print()
        for arg, shortcut, default, argtype in arguments:
            if isinstance(default, bool):
                print('    %s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg
                ))
            else:
                print('    %-30s%-10s%s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg,
                    argtype, default
                ))
        print() 
Example 22
Project: sublime-simple-import   Author: vinpac   File: JavascriptInterpreter.py    (license) View Source Project 6 votes vote down vote up
def onSearchResultChosen(self, interpreted, option_key, value, mode=SIMode.REPLACE_MODE):
    statements = interpreted.statements
    if ((mode == SIMode.PANEL_MODE and len(statements['variable'])) or
      option_key in ["exports", "module_exports"]
    ):
      interpreted.handler_name = "import_from"
      statements['submodules'] = self.parseSubmodulesKey(
        interpreted.statements['variable']
      )
      del statements['variable']
    elif mode == SIMode.PANEL_MODE:
      if option_key != "modules":
        statements['variable'] = path.basename(value)
      else:
        statements['variable'] = value

      statements['variable'] = self.parseVariableKey(
        self.removeExtensions(statements['variable'])
      )

    statements['module'] = self.parseModuleKey(value) 
Example 23
Project: hostapd-mana   Author: adde88   File: usage.py    (license) View Source Project 6 votes vote down vote up
def getSynopsis(self):
        """ Returns a string containing a description of these options and how to
            pass them to the executed file.
        """

        default = "%s%s" % (path.basename(sys.argv[0]),
                            (self.longOpt and " [options]") or '')
        if self.parent is None:
            default = "Usage: %s%s" % (path.basename(sys.argv[0]),
                                       (self.longOpt and " [options]") or '')
        else:
            default = '%s' % ((self.longOpt and "[options]") or '')
        synopsis = getattr(self, "synopsis", default)

        synopsis = synopsis.rstrip()

        if self.parent is not None:
            synopsis = ' '.join((self.parent.getSynopsis(), self.parent.subCommand, synopsis))

        return synopsis 
Example 24
Project: hostapd-mana   Author: adde88   File: filepath.py    (license) View Source Project 6 votes vote down vote up
def siblingExtensionSearch(self, *exts):
        """Attempt to return a path with my name, given multiple possible
        extensions.

        Each extension in exts will be tested and the first path which exists
        will be returned.  If no path exists, None will be returned.  If '' is
        in exts, then if the file referred to by this path exists, 'self' will
        be returned.

        The extension '*' has a magic meaning, which means "any path that
        begins with self.path+'.' is acceptable".
        """
        p = self.path
        for ext in exts:
            if not ext and self.exists():
                return self
            if ext == '*':
                basedot = basename(p)+'.'
                for fn in listdir(dirname(p)):
                    if fn.startswith(basedot):
                        return self.clonePath(joinpath(dirname(p), fn))
            p2 = p + ext
            if exists(p2):
                return self.clonePath(p2) 
Example 25
Project: hostapd-mana   Author: adde88   File: gtk2manhole.py    (license) View Source Project 6 votes vote down vote up
def _on_aboutMenuItem_activate(self, widget, *unused):
        import sys
        from os import path
        self.output.append("""\
a Twisted Manhole client
  Versions:
    %(twistedVer)s
    Python %(pythonVer)s on %(platform)s
    GTK %(gtkVer)s / PyGTK %(pygtkVer)s
    %(module)s %(modVer)s
http://twistedmatrix.com/
""" % {'twistedVer': copyright.longversion,
       'pythonVer': sys.version.replace('\n', '\n      '),
       'platform': sys.platform,
       'gtkVer': ".".join(map(str, gtk.gtk_version)),
       'pygtkVer': ".".join(map(str, gtk.pygtk_version)),
       'module': path.basename(__file__),
       'modVer': __version__,
       }, "local") 
Example 26
Project: enigma2   Author: OpenLD   File: IO.py    (license) View Source Project 6 votes vote down vote up
def saveFile(filename, data, mode=0644):
	tmpFilename = None
	try:
		f = NamedTemporaryFile(prefix='.%s.' % path.basename(filename), dir=path.dirname(filename), delete=False)
		tmpFilename = f.name
		if isinstance(data, list):
			for x in data:
				f.write(x)
		else:
			f.write(data)
		f.flush()
		fsync(f.fileno())
		fchmod(f.fileno(), mode)
		f.close()
		rename(tmpFilename, filename)
	except Exception as e:
		print 'saveFile: failed to write to %s: %s' % (filename, e)
		if tmpFilename and path.exists(tmpFilename):
			unlink(tmpFilename)
		return False

	return True 
Example 27
Project: python-lunrclient   Author: rackerlabs   File: subcommand.py    (license) View Source Project 6 votes vote down vote up
def run(self, args=None, prog=None):
        # use sys.argv if not supplied
        if not args:
            prog = basename(sys.argv[0])
            args = sys.argv[1:]
        self.prog = prog

        # If completion token found in args
        if '--bash-completion' in args:
            return self.bash_completion(args)

        # If bash completion script requested
        if '--bash-completion-script' in args:
            return self.bash_completion_script(prog)

        # Find a subcommand in the arguments
        for index, arg in enumerate(args):
            if arg in self.sub_commands.keys():
                # Remove the sub command argument
                args.pop(index)
                # Run the sub-command passing the remaining arguments
                return self.sub_commands[arg](args, prog)

        # Unable to find a suitable sub-command
        return self.help() 
Example 28
Project: DeblurGAN   Author: KupynOrest   File: get_data.py    (license) View Source Project 6 votes vote down vote up
def _download_data(self, dataset_url, save_path):
        if not isdir(save_path):
            os.makedirs(save_path)

        base = basename(dataset_url)
        temp_save_path = join(save_path, base)

        with open(temp_save_path, "wb") as f:
            r = requests.get(dataset_url)
            f.write(r.content)

        if base.endswith('.tar.gz'):
            obj = tarfile.open(temp_save_path)
        elif base.endswith('.zip'):
            obj = ZipFile(temp_save_path, 'r')
        else:
            raise ValueError("Unknown File Type: {0}.".format(base))

        self._print("Unpacking Data...")
        obj.extractall(save_path)
        obj.close()
        os.remove(temp_save_path) 
Example 29
Project: Sci-Finder   Author: snverse   File: script.py    (license) View Source Project 6 votes vote down vote up
def print_usage(actions):
    """Print the usage information.  (Help screen)"""
    _deprecated()
    actions = sorted(iteritems(actions))
    print('usage: %s <action> [<options>]' % basename(sys.argv[0]))
    print('       %s --help' % basename(sys.argv[0]))
    print()
    print('actions:')
    for name, (func, doc, arguments) in actions:
        print('  %s:' % name)
        for line in doc.splitlines():
            print('    %s' % line)
        if arguments:
            print()
        for arg, shortcut, default, argtype in arguments:
            if isinstance(default, bool):
                print('    %s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg
                ))
            else:
                print('    %-30s%-10s%s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg,
                    argtype, default
                ))
        print() 
Example 30
Project: Sci-Finder   Author: snverse   File: script.py    (license) View Source Project 6 votes vote down vote up
def print_usage(actions):
    """Print the usage information.  (Help screen)"""
    _deprecated()
    actions = sorted(iteritems(actions))
    print('usage: %s <action> [<options>]' % basename(sys.argv[0]))
    print('       %s --help' % basename(sys.argv[0]))
    print()
    print('actions:')
    for name, (func, doc, arguments) in actions:
        print('  %s:' % name)
        for line in doc.splitlines():
            print('    %s' % line)
        if arguments:
            print()
        for arg, shortcut, default, argtype in arguments:
            if isinstance(default, bool):
                print('    %s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg
                ))
            else:
                print('    %-30s%-10s%s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg,
                    argtype, default
                ))
        print() 
Example 31
Project: harbour-sailfinder   Author: DylanVanAssche   File: script.py    (license) View Source Project 6 votes vote down vote up
def print_usage(actions):
    """Print the usage information.  (Help screen)"""
    actions = sorted(iteritems(actions))
    print('usage: %s <action> [<options>]' % basename(sys.argv[0]))
    print('       %s --help' % basename(sys.argv[0]))
    print()
    print('actions:')
    for name, (func, doc, arguments) in actions:
        print('  %s:' % name)
        for line in doc.splitlines():
            print('    %s' % line)
        if arguments:
            print()
        for arg, shortcut, default, argtype in arguments:
            if isinstance(default, bool):
                print('    %s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg
                ))
            else:
                print('    %-30s%-10s%s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg,
                    argtype, default
                ))
        print() 
Example 32
Project: harbour-sailfinder   Author: DylanVanAssche   File: script.py    (license) View Source Project 6 votes vote down vote up
def print_usage(actions):
    """Print the usage information.  (Help screen)"""
    actions = sorted(iteritems(actions))
    print('usage: %s <action> [<options>]' % basename(sys.argv[0]))
    print('       %s --help' % basename(sys.argv[0]))
    print()
    print('actions:')
    for name, (func, doc, arguments) in actions:
        print('  %s:' % name)
        for line in doc.splitlines():
            print('    %s' % line)
        if arguments:
            print()
        for arg, shortcut, default, argtype in arguments:
            if isinstance(default, bool):
                print('    %s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg
                ))
            else:
                print('    %-30s%-10s%s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg,
                    argtype, default
                ))
        print() 
Example 33
Project: PyDoc   Author: shaun-h   File: DocsetManager.py    (license) View Source Project 6 votes vote down vote up
def __getDownloadLink(self, link):
		if link == 'SproutCore.xml':
			data=requests.get('http://docs.sproutcore.com/feeds/' + link).text
			e = xml.etree.ElementTree.fromstring(data)
			version = e.findall('version')[0].text
			for atype in e.findall('url'):
				return {'url': atype.text, 'version':version}
		server = self.serverManager.getDownloadServer(self.localServer)
		data = requests.get(server.url+link).text
		e = xml.etree.ElementTree.fromstring(data)
		version = e.findall('version')[0].text
		for atype in e.findall('url'):
			if not self.localServer == None:
				disassembled = urlparse(atype.text)
				filename, file_ext = splitext(basename(disassembled.path))
				url = self.localServer
				if not url[-1] == '/':
					url = url + '/'
				url = url + filename + file_ext
				return {'url': url, 'version':version}
			if atype.text.find(server.url) >= 0:
				return {'url': atype.text, 'version':version} 
Example 34
Project: better-apidoc   Author: goerz   File: better_apidoc.py    (license) View Source Project 6 votes vote down vote up
def shall_skip(module, opts):
    # type: (unicode, Any) -> bool
    """Check if we want to skip this module."""
    # skip if the file doesn't exist and not using implicit namespaces
    if not opts.implicit_namespaces and not path.exists(module):
        return True

    # skip it if there is nothing (or just \n or \r\n) in the file
    if path.exists(module) and path.getsize(module) <= 2:
        return True

    # skip if it has a "private" name and this is selected
    filename = path.basename(module)
    if filename != '__init__.py' and filename.startswith('_') and \
       not opts.includeprivate:
        return True
    return False 
Example 35
Project: argparseinator   Author: ellethee   File: __main__.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, name, dest, description=None):
        self.name = name
        wholetitle = "{} :core:`{}.{}`".format(
            name.title(), basename(dirname(dest)), name)
        wholetitlemark = "=" * len(wholetitle)
        description = description or ''
        self.info = dict(
            prj_name=name,
            prj_title=name.title(),
            prj_titlemark="=" * len(name.title()),
            mod_path=name,
            title=name.title(),
            titlemark="=" * len(name.title()),
            wholetitle=wholetitle,
            wholetitlemark=wholetitlemark,
            description=description,
        )
        super(DevFormatter, self).__init__() 
Example 36
Project: libmozdata   Author: mozilla   File: gmail.py    (license) View Source Project 6 votes vote down vote up
def send(To, Subject, Body, Cc=[], Bcc=[], html=False, files=[]):
    """Send an email
    """
    subtype = 'html' if html else 'plain'
    message = MIMEMultipart()
    message['To'] = ', '.join(To)
    message['Subject'] = Subject
    message['Cc'] = ', '.join(Cc)
    message['Bcc'] = ', '.join(Bcc)

    message.attach(MIMEText(Body, subtype))

    for f in files:
        with open(f, "rb") as In:
            part = MIMEApplication(In.read(), Name=basename(f))
            part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
            message.attach(part)

    message = {'raw': base64.urlsafe_b64encode(message.as_string())}

    credentials = oauth2client.file.Storage(CREDENTIALS_PATH).get()
    Http = credentials.authorize(httplib2.Http())
    service = discovery.build('gmail', 'v1', http=Http)

    message = service.users().messages().send(userId='me', body=message).execute() 
Example 37
Project: Texty   Author: sarthfrey   File: script.py    (license) View Source Project 6 votes vote down vote up
def print_usage(actions):
    """Print the usage information.  (Help screen)"""
    actions = sorted(iteritems(actions))
    print('usage: %s <action> [<options>]' % basename(sys.argv[0]))
    print('       %s --help' % basename(sys.argv[0]))
    print()
    print('actions:')
    for name, (func, doc, arguments) in actions:
        print('  %s:' % name)
        for line in doc.splitlines():
            print('    %s' % line)
        if arguments:
            print()
        for arg, shortcut, default, argtype in arguments:
            if isinstance(default, bool):
                print('    %s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg
                ))
            else:
                print('    %-30s%-10s%s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg,
                    argtype, default
                ))
        print() 
Example 38
Project: minc_keras   Author: tfunck   File: set_images.py    (license) View Source Project 6 votes vote down vote up
def gather_dirs(source_dir, input_str='acq', ext='mnc'):
    ''' This function takes a source directory and parse it to extract the
        information and returns it as lists of strings.

    Args:
        source_dir (str): the directory where the data is
        input_str (str): string that uniquely identifies the input (pet) images in subject directory
        ext (str) : string the identifies extension of file (default==nifti)

    Returns:
        subject_dir (list of str): a list of directories, one per subject
        pet_list (list of str): a list of directories, one per pet image
        t1_list (list of str): a list of directories, one per t1 image
        names (list of str): a list of subject names
    '''

    subject_dirs = glob(source_dir + os.sep + '*', recursive=True)
    pet_list = glob(source_dir + os.sep + '**' + os.sep + '*'+input_str+'.'+ext, recursive=True)
    if len(pet_list) == 0 : print('Warning: could not find input file of form:', source_dir + os.sep + '**' + os.sep + '*_'+input_str+'.'+ext)
    #t1_list = glob(source_dir + os.sep + '**' + os.sep + "*_T1w" + '.' +ext, recursive=True)
    names = [basename(f) for f in subject_dirs]
    #return(subject_dirs, pet_list, t1_list, names)
    return(subject_dirs, pet_list, names) 
Example 39
Project: minc_keras   Author: tfunck   File: predict.py    (license) View Source Project 6 votes vote down vote up
def set_output_image_fn(pet_fn, predict_dir, verbose=1):
    '''
        set output directory for subject and create filename for image slices. 
        output images are saved according to <predict_dir>/<subject name>/...png

        args:
            pet_fn -- filename of pet image on which prection was based
            predict_dir -- output directory for predicted images
            verbose -- print output filename if 2 or greater, 0 by default

        return:
            image_fn -- output filename for slices
    '''
    pet_basename = splitext(basename(pet_fn))[0]
    name=[ f for f in pet_basename.split('_') if 'sub' in f.split('-') ][0]
    
    image_fn = predict_dir +os.sep + pet_basename + '_predict.png'
    
    if verbose >= 2 : print('Saving to:', image_fn) 
    
    return image_fn 
Example 40
Project: auditwheel   Author: pypa   File: elfutils.py    (license) View Source Project 6 votes vote down vote up
def elf_is_python_extension(fn, elf) -> Tuple[bool, Optional[int]]:
    modname = basename(fn).split('.', 1)[0]
    module_init_f = {'init' + modname: 2, 'PyInit_' + modname: 3}

    sect = elf.get_section_by_name('.dynsym')
    if sect is None:
        return False, None

    for sym in sect.iter_symbols():
        if (sym.name in module_init_f and
                sym['st_shndx'] != 'SHN_UNDEF' and
                sym['st_info']['type'] == 'STT_FUNC'):

            return True, module_init_f[sym.name]

    return False, None 
Example 41
Project: arithmancer   Author: google   File: script.py    (license) View Source Project 6 votes vote down vote up
def print_usage(actions):
    """Print the usage information.  (Help screen)"""
    actions = actions.items()
    actions.sort()
    print('usage: %s <action> [<options>]' % basename(sys.argv[0]))
    print('       %s --help' % basename(sys.argv[0]))
    print()
    print('actions:')
    for name, (func, doc, arguments) in actions:
        print('  %s:' % name)
        for line in doc.splitlines():
            print('    %s' % line)
        if arguments:
            print()
        for arg, shortcut, default, argtype in arguments:
            if isinstance(default, bool):
                print('    %s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg
                ))
            else:
                print('    %-30s%-10s%s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg,
                    argtype, default
                ))
        print() 
Example 42
Project: apio   Author: FPGAwars   File: installer.py    (license) View Source Project 6 votes vote down vote up
def _download(self, url):
        # Note: here we check only for the version of locally installed
        # packages. For this reason we don't say what's the installation
        # path.
        if self.profile.check_package_version(self.package, self.version) \
           or self.force_install:
            fd = FileDownloader(url, self.packages_dir)
            filepath = fd.get_filepath()
            click.secho('Download ' + basename(filepath))
            try:
                fd.start()
            except KeyboardInterrupt:
                if isfile(filepath):
                    remove(filepath)
                click.secho('Abort download!', fg='red')
                exit(1)
            return filepath
        else:
            click.secho('Already installed. Version {0}'.format(
                self.profile.get_package_version(self.package)), fg='yellow')
            return None 
Example 43
Project: tesismometro   Author: joapaspe   File: script.py    (license) View Source Project 6 votes vote down vote up
def print_usage(actions):
    """Print the usage information.  (Help screen)"""
    actions = sorted(iteritems(actions))
    print('usage: %s <action> [<options>]' % basename(sys.argv[0]))
    print('       %s --help' % basename(sys.argv[0]))
    print()
    print('actions:')
    for name, (func, doc, arguments) in actions:
        print('  %s:' % name)
        for line in doc.splitlines():
            print('    %s' % line)
        if arguments:
            print()
        for arg, shortcut, default, argtype in arguments:
            if isinstance(default, bool):
                print('    %s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg
                ))
            else:
                print('    %-30s%-10s%s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg,
                    argtype, default
                ))
        print() 
Example 44
Project: veros   Author: dionhaefner   File: conf.py    (license) View Source Project 6 votes vote down vote up
def run(self):
        oldStdout, sys.stdout = sys.stdout, StringIO()

        tab_width = self.options.get('tab-width', self.state.document.settings.tab_width)
        source = self.state_machine.input_lines.source(self.lineno - self.state_machine.input_offset - 1)

        try:
            exec('\n'.join(self.content))
            text = sys.stdout.getvalue()
            lines = statemachine.string2lines(text, tab_width, convert_whitespace=True)
            self.state_machine.insert_input(lines, source)
            return []
        except Exception:
            return [nodes.error(None, nodes.paragraph(text = "Unable to execute python code at %s:%d:" % (basename(source), self.lineno)), nodes.paragraph(text = str(sys.exc_info()[1])))]
        finally:
            sys.stdout = oldStdout 
Example 45
Project: newsreap   Author: caronc   File: NNTPnzb_Test.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def test_nzbfile_generation(self):
        """
        Tests the creation of NZB Files
        """
        nzbfile = join(self.tmp_dir, 'test.nzbfile.nzb')
        payload = join(self.var_dir, 'uudecoded.tax.jpg')
        assert isfile(nzbfile) is False
        # Create our NZB Object
        nzbobj = NNTPnzb()

        # create a fake article
        segpost = NNTPSegmentedPost(basename(payload))
        content = NNTPBinaryContent(payload)

        article = NNTPArticle('testfile', groups='newsreap.is.awesome')

        # Note that our nzb object segment tracker is not marked as being
        # complete. This flag gets toggled when we add segments manually to
        # our nzb object or if we parse an NZB-File
        assert(nzbobj._segments_loaded is None)

        # Add our Content to the article
        article.add(content)
        # now add our article to the NZBFile
        segpost.add(article)
        # now add our Segmented Post to the NZBFile
        nzbobj.add(segpost)

        # Since .add() was called, this will be set to True now
        assert(nzbobj._segments_loaded is True)

        # Store our file
        assert nzbobj.save(nzbfile) is True
        assert isfile(nzbfile) is True 
Example 46
Project: newsreap   Author: caronc   File: CodecFile.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def watch_dir(self, path, regex=None, prefix=None, suffix=None,
            ignore=None, case_sensitive=True, seconds=15):
        """Monitors a directory for files that have been added/changed

            path: is the path to monitor
            ignore: is a sortedset of files already parsed
            seconds: is how long it takes a file to go untouched for before
              we presume it has been completely written to disk.
        """

        if ignore is None:
            ignore = sortedset()

        findings = find(
            path, fsinfo=True,
            regex_filter=regex,
            prefix_filter=prefix,
            suffix_filter=suffix,
            case_sensitive=case_sensitive,
        )

        findings = [
            (p, f['size'], f['created'], f['modified'])
                for p, f in findings.items()
                  if (f['modified'] - f['created']).total_seconds() >= seconds
                    and f['basename'] not in ignore
        ]

        # Sort list by created date
        findings.sort(key=lambda x: x[3])

        for f in findings:
            logger.info('Created %s (size=%s)' % (
                f, bytes_to_strsize(f[1]),
            ))
            # Add to our filter list
            ignore.add(f[0])

        # Return our ignore list (which is acutally also a found list)
        return ignore 
Example 47
Project: newsreap   Author: caronc   File: NNTPnzb.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def deobsfucate(self, filebase=None):
        """
        Scans through the segments, articles and content associated with an
        NZB-File and sets up the filenames defined in the segments to it's
        best effort

        filebase: provide a fallback filename base (the part of the file
                  before the extension) to build on if we can't detect
                  the file on our own.

        """
        # The name from the meta tag
        _name = self.meta.get('name', '').decode(self.encoding).strip()
        if not _name:
            if filebase:
                # Use base provided as a base
                _name = filebase

            else:
                # If we can't get a name from the meta tag to start with, then
                # we use the NZB-Filename itself as a backup
                _name = splitext(basename(self.path()))[0]

        for segment in self.segments:
            filename = segment.deobsfucate(_name)
            if filename:
                # Update
                segment.filename = filename 
Example 48
Project: pynini   Author: daffidilly   File: setup.py    (license) View Source Project 5 votes vote down vote up
def determine(argv=None):
        argv = argv or sys.argv  # use command-line flags if nothing else passed

        arg_parser = ArgumentParser(prog='pynini', description='Static site processor')
        arg_parser.add_argument('--verbosity', '-v', action='count', help='increase log verbosity', default=0)
        arg_parser.add_argument('--dist', metavar='dist_dir', help='specify dist directory (disable auto detect)', default=None)
        arg_parser.add_argument('--src', '-s', metavar='src_dir', help='specify src directory (disable auto detect)', default=None)
        arg_parser.add_argument('--pages', metavar='pages_dir', help='specify pages directory (disable auto detect)', default=None)
        arg_parser.add_argument('--layouts', metavar='layouts_dir', help='specify layouts directory (disable auto detect)', default=None)
        arg_parser.add_argument('--partials', metavar='partials_dir', help='specify partials directory (disable auto detect)', default=None)
        parsed_args = arg_parser.parse_args(argv[1:])
        # print(parsed_args)

        # each of the below can be None
        dist_dir = parsed_args.dist
        src_dir = parsed_args.src
        pages_dir = parsed_args.pages
        layouts_dir = parsed_args.layouts
        partials_dir = parsed_args.partials

        operation_dir = getcwd()
        if isdir(join(operation_dir, 'src')):
            src_dir = src_dir or join(operation_dir, 'src')
            dist_dir = dist_dir or join(operation_dir, 'dist')

        elif 'src' == basename(operation_dir):  # we're inside the src dir
            src_dir = src_dir or operation_dir
            dist_dir = dist_dir or join(dirname(operation_dir), 'dist')

        elif not src_dir or not dist_dir:
            raise SetupError('Could not determine src_dir, dist_dir')

        return Setup(operation_dir,
                     dist_dir,
                     src_dir,
                     pages_dir=pages_dir,
                     layouts_dir=layouts_dir,
                     partials_dir=partials_dir,
                     verbosity=parsed_args.verbosity,
                     template_loader=None,
                     template_writer=None) 
Example 49
Project: picoCTF   Author: picoCTF   File: daemon_manager.py    (MIT License) View Source Project 5 votes vote down vote up
def load_modules(directory):
    files = glob.glob("{}/*.py".format(directory))
    return [imp.load_source(splitext(basename(module))[0], module) for module in files] 
Example 50
Project: personal-identification-pipeline   Author: TeamErlich   File: poretools-basenames.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def process_times(filename):
    """
    Remove the path (dirname) from the second field of the 'times' file.
    """
    try:
        f=open(filename,'r')
        for linenum,line in enumerate(f):
            err = "input error in '%s' line %d: " % (filename, linenum+1)

            line = line.strip()
            flds = line.split('\t')
            if len(flds) != 11:
                sys.exit(err + "expecting 11 fields, found %d - is this a " \
                         "'poretools times' file?" % (len(flds)))

            # First line: validate, then print as-is
            if linenum==0:
                if flds[0] != "channel":
                    sys.exit(err + "expecting header line (first word: " \
                             "'channel') - is this a 'poretools times' file?")
                print '\t'.join(flds)
                continue


            # other lines - remove path from second field.
            flds[1] = basename(flds[1])
            print '\t'.join(flds)


    except IOError as e:
        if e.errno == errno.EPIPE:
            sys.exit(0) # exit silently

        # TODO: this is a cop-out, hard to tell what's the exact error
        #       and give informative,useful error message to the user.
        sys.exit("I/O error: %s" % (str(e)))