当前位置: 首页>>代码示例>>Python>>正文


Python path.dirname函数代码示例

本文整理汇总了Python中os.path.dirname函数的典型用法代码示例。如果您正苦于以下问题:Python dirname函数的具体用法?Python dirname怎么用?Python dirname使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了dirname函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: download_file

def download_file(url, name, root_destination='~/data/', zipfile=False,
                  replace=False):
    """Download a file from dropbox, google drive, or a URL.

    This will download a file and store it in a '~/data/` folder,
    creating directories if need be. It will also work for zip
    files, in which case it will unzip all of the files to the
    desired location.

    Parameters
    ----------
    url : string
        The url of the file to download. This may be a dropbox
        or google drive "share link", or a regular URL. If it
        is a share link, then it should point to a single file and
        not a folder. To download folders, zip them first.
    name : string
        The name / path of the file for the downloaded file, or
        the folder to zip the data into if the file is a zipfile.
    root_destination : string
        The root folder where data will be downloaded.
    zipfile : bool
        Whether the URL points to a zip file. If yes, it will be
        unzipped to root_destination + name.
    replace : bool
        If True and the URL points to a single file, overwrite the
        old file if possible.
    """
    # Make sure we have directories to dump files
    home = op.expanduser('~')
    tmpfile = home + '/tmp/tmp'
    if not op.isdir(home + '/data/'):
        print('Creating data folder...')
        os.makedirs(home + '/data/')

    if not op.isdir(home + '/tmp/'):
        print('Creating tmp folder...')
        os.makedirs(home + '/tmp/')

    download_path = _convert_url_to_downloadable(url)

    # Now save to the new destination
    out_path = root_destination.replace('~', home) + name
    if not op.isdir(op.dirname(out_path)):
        print('Creating path {} for output data'.format(out_path))
        os.makedirs(op.dirname(out_path))

    if zipfile is True:
        _fetch_file(download_path, tmpfile)
        myzip = ZipFile(tmpfile)
        myzip.extractall(out_path)
        os.remove(tmpfile)
    else:
        if len(name) == 0:
            raise ValueError('Cannot overwrite the root data directory')
        if replace is False and op.exists(out_path):
            raise ValueError('Path {} exists, use `replace=True` to '
                             'overwrite'.format(out_path))
        _fetch_file(download_path, out_path)
    print('Successfully moved file to {}'.format(out_path))
开发者ID:data-8,项目名称:connector-instructors,代码行数:60,代码来源:utils.py

示例2: make_image_path

def make_image_path(outdoc, src):
    filename = outdoc.name
    basedir = join(dirname(filename), dirname(src))
    if not exists(basedir):
        makedirs(basedir)
    path = join(dirname(filename), src)
    return path
开发者ID:RB14,项目名称:lpod-python,代码行数:7,代码来源:lpod-convert.py

示例3: handle_page

    def handle_page(self, pagename, ctx, templatename='page.html',
                    outfilename=None, event_arg=None):
        ctx['current_page_name'] = pagename
        sidebarfile = self.config.html_sidebars.get(pagename)
        if sidebarfile:
            ctx['customsidebar'] = sidebarfile

        if not outfilename:
            outfilename = path.join(self.outdir,
                                    os_path(pagename) + self.out_suffix)

        self.app.emit('html-page-context', pagename, templatename,
                      ctx, event_arg)

        ensuredir(path.dirname(outfilename))
        f = open(outfilename, 'wb')
        try:
            self.implementation.dump(ctx, f, 2)
        finally:
            f.close()

        # if there is a source file, copy the source file for the
        # "show source" link
        if ctx.get('sourcename'):
            source_name = path.join(self.outdir, '_sources',
                                    os_path(ctx['sourcename']))
            ensuredir(path.dirname(source_name))
            copyfile(self.env.doc2path(pagename), source_name)
开发者ID:89sos98,项目名称:main,代码行数:28,代码来源:html.py

示例4: test_get_set_sample_network

    def test_get_set_sample_network(self):
        ndex = nc.Ndex(host= tt.TESTSERVER, username=tt.testUser1, password=tt.testUserpasswd, debug=True)

        with open(path.join(path.abspath(path.dirname(__file__)),example_network_1), 'r') as file_handler:
            network_in_cx = file_handler.read()

        # test save_cx_stream_as_new_network
        test_network_1_uri = ndex.save_cx_stream_as_new_network(network_in_cx)
        self.assertTrue(test_network_1_uri.startswith(tt.TESTSERVER + ndex_network_resource))

        network_UUID = str(test_network_1_uri.split("/")[-1])

        time.sleep(20)

        with open(path.join(path.abspath(path.dirname(__file__)),sample_network), 'r') as file_handler:
            sample_cx = file_handler.read()
        ndex.set_network_sample(network_UUID, sample_cx)

        time.sleep(3)
        # get network summary with the new properties
        sample_from_server = ndex.get_sample_network(network_UUID)
        putJson = json.loads(sample_cx)
        self.assertTrue(len(putJson) == len(sample_from_server))


        # test delete_network
        del_network_return = ndex.delete_network(network_UUID)
        self.assertTrue(del_network_return == '')
开发者ID:ndexbio,项目名称:ndex-python,代码行数:28,代码来源:test_set_get_sample.py

示例5: load_names

 def load_names(cls, db=None):
     """Populate the locale_label table."""
     from os.path import dirname, join
     db = db or cls.default_db
     fname = join(dirname(dirname(__file__)),
                  'nlp/data/language-names.json')
     with open(fname) as f:
         names = json.load(f)
     locales = {x[0] for x in names}.union({x[1] for x in names})
     Locale.bulk_get_or_create(locales, db)
     db.flush()
     Locale.reset_cache()
     db.execute("lock table %s in exclusive mode" % cls.__table__.name)
     existing = set(db.query(
         cls.named_locale_id, cls.locale_id_of_label).all())
     c = Locale.locale_collection
     values = []
     for (lcode, tcode, name) in names:
         l, t = c[lcode], c[tcode]
         if (l, t) not in existing:
             values.append({
                 'named_locale_id': l,
                 'locale_id_of_label': t,
                 'name': name})
     if values:
         db.execute(cls.__table__.insert().values(values))
         db.flush()
开发者ID:assembl,项目名称:assembl,代码行数:27,代码来源:langstrings.py

示例6: _load

    def _load(self):
        log.debug("reading `%s'", self.path)
        sys.path.insert(0, dirname(self.path))
        try:
            source = open(self.path).read()
            code = compile(source, self.path, 'exec')
            globs = {
                '__builtins__': sys.modules['__builtin__'],
                '__file__': str(self.path),
                '__name__': splitext(basename(self.path))[0],
                '_mk_makefile_': self,
                #TODO: is _mk_ns_ necessary?
                '_mk_ns_': self.ns,
            }
            mod = eval(code, globs)
        finally:
            sys.path.remove(dirname(self.path))

        self.doc = mod.__doc__
        default_tasks = [t for t in self.tasks.values() if t.default]
        if not default_tasks:
            self.default_task = None
        elif len(default_tasks) == 1:
            self.default_task = default_tasks[0]
        else:
            raise IllegalMakefileError("more than one default task: %s"
                                       % ', '.join(map(str, default_tasks)))
开发者ID:Acidburn0zzz,项目名称:KomodoEdit,代码行数:27,代码来源:makefile.py

示例7: test_permissions_warnings

    def test_permissions_warnings(self):
        """Make sure letsencrypt-auto properly warns about permissions problems."""
        # This test assumes that only the parent of the directory containing
        # letsencrypt-auto (usually /tmp) may have permissions letsencrypt-auto
        # considers insecure.
        with temp_paths() as (le_auto_path, venv_dir):
            le_auto_path = abspath(le_auto_path)
            le_auto_dir = dirname(le_auto_path)
            le_auto_dir_parent = dirname(le_auto_dir)
            install_le_auto(self.NEW_LE_AUTO, le_auto_path)

            run_letsencrypt_auto = partial(
                run_le_auto, le_auto_path, venv_dir,
                le_auto_args_str='--install-only --no-self-upgrade',
                PIP_FIND_LINKS=join(tests_dir(), 'fake-letsencrypt', 'dist'))
            # Run letsencrypt-auto once with current permissions to avoid
            # potential problems when the script tries to write to temporary
            # directories.
            run_letsencrypt_auto()

            le_auto_dir_mode = stat(le_auto_dir).st_mode
            le_auto_dir_parent_mode = S_IMODE(stat(le_auto_dir_parent).st_mode)
            try:
                # Make letsencrypt-auto happy with the current permissions
                chmod(le_auto_dir, S_IRUSR | S_IXUSR)
                sudo_chmod(le_auto_dir_parent, 0o755)

                self._test_permissions_warnings_about_path(le_auto_path, run_letsencrypt_auto)
                self._test_permissions_warnings_about_path(le_auto_dir, run_letsencrypt_auto)
            finally:
                chmod(le_auto_dir, le_auto_dir_mode)
                sudo_chmod(le_auto_dir_parent, le_auto_dir_parent_mode)
开发者ID:certbot,项目名称:certbot,代码行数:32,代码来源:auto_test.py

示例8: test_tree_determinism

    def test_tree_determinism(self):
        """Check that the tree is drawn identically upon receiving the same
        dataset with no parameter changes."""
        n_tries = 10
        # Make sure the tree are deterministic for iris
        scene_nodes = []
        for _ in range(n_tries):
            self.send_signal(self.widget.Inputs.tree, self.signal_data)
            scene_nodes.append([n.pos() for n in self.get_visible_squares()])
        for node_row in zip(*scene_nodes):
            self.assertTrue(
                self._check_all_same(node_row),
                "The tree was not drawn identically in the %d times it was "
                "sent to widget after receiving the iris dataset." % n_tries
            )

        # Make sure trees are deterministic with data where some variables have
        # the same entropy
        data_same_entropy = Table(path.join(
            path.dirname(path.dirname(path.dirname(__file__))), "tests",
            "datasets", "same_entropy.tab"))
        data_same_entropy = TreeLearner()(data_same_entropy)
        scene_nodes = []
        for _ in range(n_tries):
            self.send_signal(self.widget.Inputs.tree, data_same_entropy)
            scene_nodes.append([n.pos() for n in self.get_visible_squares()])
        for node_row in zip(*scene_nodes):
            self.assertTrue(
                self._check_all_same(node_row),
                "The tree was not drawn identically in the %d times it was "
                "sent to widget after receiving a dataset with variables with "
                "same entropy." % n_tries
            )
开发者ID:astaric,项目名称:orange3,代码行数:33,代码来源:test_owpythagorastree.py

示例9: main

def main():
    """Main method.
    """
    global TCloc,volume,keyspace,keylen,nptot,permutation,passphrase,done,nperm
    if(len(sys.argv) < 3):
        print "Usage: johnny.py [path to TrueCrypt volume] [set of possible first characters] [set of possible second characters] ...\n"
        print "Recover a TrueCrypt password based on a rememberd mnemonic. Pass johnny.py a space-delineated list of strings each"
        print "representing the set of possible characters for each character in the password. If your passphrase contains a space, use quotes ;-)"
        sys.exit(0)
    TCloc = ((subprocess.Popen(['which','truecrypt'],stdout=subprocess.PIPE)).communicate())[0][0:-1]
    volume=sys.argv[1]
    keyspace = sys.argv[2:]
    keylen = len(keyspace)
    nptot = reduce(lambda x, y: x*y,[len(chars) for chars in keyspace])
    permutation = ['' for x in keyspace]
    done = 0
    nperm = 0

    if (not path.exists(path.dirname(volume))):
        print('File ' + volume + ': no such file or directory.')
    elif (not path.exists(volume)):
        print('File ' + volume + ': not found in ' + path.dirname(volume))
    else:
        passfile = open('pass.txt','w')
        print("Trying each of the %d possible keys..." % nptot)
        if(tryKey(0)):
            print('Successfully determined TrueCrypt password: ' + passphrase)
            passfile.write(passphrase)
            passfile.close()
        else:
            print('Did not succeed in finding TrueCrypt password in specified keyspace.')
开发者ID:Deconstrained,项目名称:Johnny,代码行数:31,代码来源:johnny.py

示例10: loadController

 def loadController(self, filename):
     fName = splitext(filename)
     if(fName[1] == ".py"):
         self.execfile(filename)
         for x in dir():
             if(isinstance(eval(x),type)):
                 if(issubclass(eval(x),IRobotController) and x != "IRobotController"):
                     for i in inspect.getmembers(__import__(x)):
                         if inspect.isclass(i[1]):
                             if (issubclass(i[1],IRobotController) and i[0]!="IRobotController"):
                                 r = i[1]()
                                 return r
                 elif(hasattr(eval(x),'controlRobot')):
                     pcw = PolledControllerWrapper(eval(x)())
                     for k,v in locals().items():
                         if hasattr(v,'__module__'):
                             if hasattr(sys.modules[v.__module__],'__file__'):
                                 if dirname(sys.modules[v.__module__].__file__) not in [getcwd(),""]:
                                     globals()[k] = v
                         elif k in sys.modules.keys():
                             if hasattr(sys.modules[k],'__file__'):
                                 if dirname(sys.modules[k].__file__) not in [getcwd(),""]:
                                     globals()[k] = v
                     return pcw
     else:
         raise RuntimeError("File given is not a Python file")
开发者ID:Apc204,项目名称:GroupProject,代码行数:26,代码来源:MazeLogic.py

示例11: scraper

def scraper(config_file, queue):
    try:
        # START
        sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
        short_name = get_output_json_name(config_file)
        output_file = os.path.join(OUTPUT_JSON_PATH, short_name)
        suspect_urls_log = os.path.join(LOGS_PATH, short_name.replace(".json", "_error_urls.log"))
        log_file = os.path.join(LOGS_PATH, short_name.replace(".json", ".log"))
        limit = LIMIT if LIMIT else -1
        #print "Starting : %s " % (config_file)
        command = "scrapy crawl web_scraper -a config_file=%s -s LOG_FILE=%s -a suspect_urls_log=%s -o %s -a summary=default -a limit=%s " % (
            config_file, log_file, suspect_urls_log, output_file, limit)
        print command + "\n"
        if S3:
            command = "%s -a compress=%s -a s3=%s" % (command, COMPRESS_PATH, S3)
        collector = StatsCollector(config_file=config_file, output_file=output_file)
        queue.put(collector)
        call(command, shell=True)
        # get data generate from sub process
        summary_path = collector.default_path()
        with open(summary_path) as summary_file:
            json_value = json.load(summary_file)
            collector = StatsCollector.load_from_json(json_value=json_value)
        queue.put(collector)

    except:
        traceback.print_exc()
        print "Error when processing the job for %s" % (config_file)
        pass
开发者ID:bangnguyen,项目名称:analyse_trames,代码行数:29,代码来源:run_all.py

示例12: getIcons

def getIcons(filename=None):
    """Creates wxBitmaps ``self.icon`` and ``self.iconAdd`` based on the the image.
    The latter has a plus sign added over the top.

    png files work best, but anything that wx.Image can import should be fine
    """
    icons = {}
    if filename is None:
        filename = join(dirname(abspath(__file__)), 'base.png')
        
    # get the low-res version first
    im = Image.open(filename)
    icons['24'] = pilToBitmap(im, scaleFactor=0.5)
    icons['24add'] = pilToBitmap(im, scaleFactor=0.5)
    # try to find a 128x128 version
    filename128 = filename[:-4]+'128.png'
    if False: # TURN OFF FOR NOW os.path.isfile(filename128):
        im = Image.open(filename128)
    else:
        im = Image.open(filename)
    icons['48'] = pilToBitmap(im)
    # add the plus sign
    add = Image.open(join(dirname(abspath(__file__)), 'add.png'))
    im.paste(add, [0, 0, add.size[0], add.size[1]], mask=add)
    # im.paste(add, [im.size[0]-add.size[0], im.size[1]-add.size[1],
    #               im.size[0], im.size[1]], mask=add)
    icons['48add'] = pilToBitmap(im)

    return icons
开发者ID:andela-dowoade,项目名称:psychopy,代码行数:29,代码来源:__init__.py

示例13: setUp

 def setUp(self):
     # Every test needs access to the request factory.
     self.url = reverse('receive_inbound_email')
     self.factory = RequestFactory()
     self.parser = MailgunRequestParser()
     self.test_upload_txt = path.join(path.dirname(__file__), 'test_files/test_upload_file.txt')
     self.test_upload_png = path.join(path.dirname(__file__), 'test_files/test_upload_file.jpg')
开发者ID:series7,项目名称:django-inbound-email,代码行数:7,代码来源:tests.py

示例14: filter_move

def filter_move(path_old, path_new):
    if dirname(path_old) == dirname(path_new):
        label = "rename"
        path_new = basename(path_new)
    else:
        label = "move"
    return "%s %s to %s" % (T.green(label), T.underline(path_old), T.underline(path_new)), 0
开发者ID:liuchuan98,项目名称:maybe,代码行数:7,代码来源:move.py

示例15: test_write1

	def test_write1(self):
		fname = '___testwrite1__99001324.scn'
		G = scn.read(path.join(path.dirname(__file__),'test1.scn'),directed=False)
		
		self.assertEqual(G.node_data('a')[0],'1')
		self.assertEqual(G.node_data('a')[1],'1')
		
		# write all attributes back
		scn.write(	G,fname,num_node_props=2,num_edge_props=2,
					node_data_fxn=lambda idx,nobj,data: None if data == None else tuple([a for a in data]),
					edge_data_fxn=lambda idx,n1,n2,data: tuple([a for a in data]))
		G = scn.read(fname,directed=False)
		
		self.assertEqual(len(G),5)
		self.assertEqual(G.size(),5)
		
		self.assertNotEqual(G.node_data('a'),None)
		self.assertEqual(G.node_data('a')[0],'1')
		self.assertEqual(G.edge_data('a','b')[0],'X')
		
		# write with no edge attributes
		G = scn.read(path.join(path.dirname(__file__),'test1.scn'),directed=False)
		scn.write(	G,fname,num_node_props=2,num_edge_props=2,
					node_data_fxn=lambda idx,nobj,data: None if data == None else tuple([a for a in data]),
					edge_data_fxn=lambda idx,n1,n2,data: None)
		G = scn.read(fname,directed=False)
		
		self.assertEqual(len(G),5)
		self.assertEqual(G.size(),5)
		
		self.assertNotEqual(G.node_data('a'),None)
		self.assertEqual(G.node_data('a')[0],'1')
		self.assertEqual(G.edge_data('a','b'),None)
		
		os.remove(fname)
开发者ID:Atomised,项目名称:zenlib,代码行数:35,代码来源:scn.py


注:本文中的os.path.dirname函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。