Python os.path 模块,basename() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用os.path.basename()

项目:cxflow-tensorflow    作者:Cognexa    | 项目源码 | 文件源码
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)
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
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
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
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
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
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()
项目:code    作者:ActiveState    | 项目源码 | 文件源码
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)
项目:code    作者:ActiveState    | 项目源码 | 文件源码
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
项目:pineapple    作者:peter765    | 项目源码 | 文件源码
def load_plugins(self):
        """
        Load all plugin files in the folder (specified by self.directory) as modules
        and into a container dictionary list.
        :return:
        """
        # Clear containers
        self.plugins.clear()
        self.commands.clear()
        self.join.clear()
        self.leave.clear()
        self.typing.clear()
        self.delete.clear()
        self.loop.clear()

        # Find all python files in the plugin directory
        modules = glob.glob(dirname(__file__) + "/" + self.dir + "/**/*.py", recursive=True)

        # Iterate over each file, import them as a Python module and add them to the plugin list
        for f in modules:
            spec = importlib.util.spec_from_file_location(basename(f)[:-3], f)
            plugin = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(plugin)
            self.plugins[basename(f)] = plugin.Plugin(self)
            print("Loaded plugin: " + basename(f))
项目:pineapple    作者:peter765    | 项目源码 | 文件源码
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
    ###
项目:pycoal    作者:capstone-coal    | 项目源码 | 文件源码
def rasterize(self, vector_filename, feature_filename):
        """
        Burn features from a vector image onto a raster image.

        Args:
            vector_filename (str):  filename of the vector image
            feature_filename (str): filename of the raster image
        """
        logging.info("Burning features from vector file: '%s' to raster file: '%s'" %(vector_filename, feature_filename))
        # assume the layer has the same name as the image
        layer_name = splitext(basename(vector_filename))[0]

        # convert vector features into nonzero pixels of the output file
        returncode = call(['gdal_rasterize',
                           '-burn', '1',
                           '-l', layer_name,
                           vector_filename,
                           feature_filename])

        # detect errors
        if returncode != 0:
            raise RuntimeError('Could not rasterize vector.')
项目:ssbio    作者:SBRG    | 项目源码 | 文件源码
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)
项目:ssbio    作者:SBRG    | 项目源码 | 文件源码
def split_folder_and_path(filepath):
    """Split a file path into its folder, filename, and extension

    Args:
        path (str): Path to a file

    Returns:
        tuple: of (folder, filename (without extension), extension)

    """
    dirname = op.dirname(filepath)
    filename = op.basename(filepath)
    splitext = op.splitext(filename)
    filename_without_extension = splitext[0]
    extension = splitext[1]

    return dirname, filename_without_extension, extension
项目:ssbio    作者:SBRG    | 项目源码 | 文件源码
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)
项目:ssbio    作者:SBRG    | 项目源码 | 文件源码
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)
项目:swjtu-pyscraper    作者:Desgard    | 项目源码 | 文件源码
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()
项目:BadParser    作者:stanojevic    | 项目源码 | 文件源码
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
项目:albt    作者:geothird    | 项目源码 | 文件源码
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:])
项目:geekcloud    作者:Mr-Linus    | 项目源码 | 文件源码
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
项目:SourceFilterContoursMelody    作者:juanjobosch    | 项目源码 | 文件源码
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)
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
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)
项目:api-manager    作者:edx    | 项目源码 | 文件源码
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
项目:sublime-text-3-packages    作者:nickjj    | 项目源码 | 文件源码
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)
项目:sublime-text-3-packages    作者:nickjj    | 项目源码 | 文件源码
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()
项目:sublime-text-3-packages    作者:nickjj    | 项目源码 | 文件源码
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
项目:zanph    作者:zanph    | 项目源码 | 文件源码
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()
项目:sublime-simple-import    作者:vinpac    | 项目源码 | 文件源码
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)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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")
项目:enigma2    作者:OpenLD    | 项目源码 | 文件源码
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
项目:python-lunrclient    作者:rackerlabs    | 项目源码 | 文件源码
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()
项目:DeblurGAN    作者:KupynOrest    | 项目源码 | 文件源码
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)
项目:Sci-Finder    作者:snverse    | 项目源码 | 文件源码
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()
项目:Sci-Finder    作者:snverse    | 项目源码 | 文件源码
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()
项目:harbour-sailfinder    作者:DylanVanAssche    | 项目源码 | 文件源码
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()
项目:harbour-sailfinder    作者:DylanVanAssche    | 项目源码 | 文件源码
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()
项目:PyDoc    作者:shaun-h    | 项目源码 | 文件源码
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}
项目:better-apidoc    作者:goerz    | 项目源码 | 文件源码
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
项目:argparseinator    作者:ellethee    | 项目源码 | 文件源码
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__()
项目:libmozdata    作者:mozilla    | 项目源码 | 文件源码
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()
项目:Texty    作者:sarthfrey    | 项目源码 | 文件源码
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()
项目:minc_keras    作者:tfunck    | 项目源码 | 文件源码
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)
项目:minc_keras    作者:tfunck    | 项目源码 | 文件源码
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
项目:pipeline    作者:liorbenhorin    | 项目源码 | 文件源码
def trash_move(src, dst, topdir=None):
    filename = op.basename(src)
    filespath = op.join(dst, FILES_DIR)
    infopath = op.join(dst, INFO_DIR)
    base_name, ext = op.splitext(filename)

    counter = 0
    destname = filename
    while op.exists(op.join(filespath, destname)) or op.exists(op.join(infopath, destname + INFO_SUFFIX)):
        counter += 1
        destname = '%s %s%s' % (base_name, counter, ext)

    check_create(filespath)
    check_create(infopath)

    os.rename(src, op.join(filespath, destname))
    f = open(op.join(infopath, destname + INFO_SUFFIX), 'w')
    f.write(info_for(src, topdir))
    f.close()
项目:auditwheel    作者:pypa    | 项目源码 | 文件源码
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
项目:arithmancer    作者:google    | 项目源码 | 文件源码
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()
项目:apio    作者:FPGAwars    | 项目源码 | 文件源码
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
项目:tesismometro    作者:joapaspe    | 项目源码 | 文件源码
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()
项目:veros    作者:dionhaefner    | 项目源码 | 文件源码
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
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def execute(self, context):
        from os.path import basename, splitext
        filepath = self.filepath

        # change the menu title to the most recently chosen option
        preset_class = getattr(bpy.types, self.menu_idname)
        preset_class.bl_label = bpy.path.display_name(basename(filepath))

        ext = splitext(filepath)[1].lower()

        # execute the preset using script.python_file_run
        if ext == ".py":
            bpy.ops.script.python_file_run(filepath=filepath)
        elif ext == ".xml":
            import rna_xml
            rna_xml.xml_file_run(context,
                                 filepath,
                                 preset_class.preset_xml_map)
        else:
            self.report({'ERROR'}, "unknown filetype: %r" % ext)
            return {'CANCELLED'}

        return {'FINISHED'}
项目:newsreap    作者:caronc    | 项目源码 | 文件源码
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