• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python tempfile._get_candidate_names函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: deep_matches_vids

def deep_matches_vids(exec_name, vid_frames_path, extra_params=""):
    all_matches = []
    # get a temporary filename
    tmp_vid_fname = next(tempfile._get_candidate_names()) + ".avi"
    tmp_fname = next(tempfile._get_candidate_names())
    ffmpeg_cmd = "ffmpeg -i %s -c:v huffyuv -pix_fmt rgb24 %s" % (vid_frames_path, tmp_vid_fname)
    cmd = '%s -i "%s" %s -b -out %s' % (exec_name, tmp_vid_fname, extra_params, tmp_fname)
    try:
        proc = subprocess.Popen(ffmpeg_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        (out, err) = proc.communicate()
        ret = proc.wait()
        t1 = datetime.now()
        ret = os.system(cmd)
        t2 = datetime.now()
        delta = t2 - t1
        #sys.stdout.write("%s - %.2fs | " % (ret, delta.seconds + delta.microseconds/1E6))
        all_matches = read_output_vid_matches_binary(tmp_fname)
    finally:
        # delete the output file if it exists
        try:
            os.remove(tmp_vid_fname)
            os.remove(tmp_fname)
        except OSError:
            pass

    return all_matches
开发者ID:ahmadh84,项目名称:extern_sync,代码行数:26,代码来源:deepmatch_unittest.py


示例2: setUp

    def setUp(self):
        if not os.path.exists(self.fixture_dir):
            os.mkdir(self.fixture_dir)

        self.tmp_file_path = os.path.join(
            self.fixture_dir, next(tempfile._get_candidate_names()))
        while os.path.exists(self.tmp_file_path):
            self.tmp_file_path = os.path.join(
                self.fixture_dir, next(tempfile._get_candidate_names()))
开发者ID:lym0302,项目名称:snips-nlu,代码行数:9,代码来源:integration_test_cli.py


示例3: processtable

def processtable(raster_obj, zone_file, w, out_folder, out_file):
  temp_name = "/" + next(tempfile._get_candidate_names()) + ".dbf"
  arcpy.sa.ZonalStatisticsAsTable(zone_file, 'VALUE', raster_obj, out_folder + temp_name, "DATA", "SUM")
  arcpy.AddField_management(out_folder + temp_name, "elev", 'TEXT')
  arcpy.CalculateField_management(out_folder + temp_name, "elev", "'" + str(w*0.1) + "'", "PYTHON")
  arcpy.TableToTable_conversion(out_folder + temp_name, out_folder, out_file)
  arcpy.Delete_management(out_folder + temp_name)
开发者ID:mkoohafkan,项目名称:rremat,代码行数:7,代码来源:topo_lookup_table.py


示例4: deep_matches_ims

def deep_matches_ims(exec_name, im1_fp, im2_fp, binary_out=False, has_num_matches=True, extra_params=""):
    matches = []
    # get a temporary filename
    tmp_fname = next(tempfile._get_candidate_names())
    if binary_out:
        extra_params += " -b"
    cmd = '%s "%s" "%s" %s -out %s' % (exec_name, im1_fp, im2_fp, extra_params, tmp_fname)
    try:
        t1 = datetime.now()
        ret = os.system(cmd)
        t2 = datetime.now()
        delta = t2 - t1
        #sys.stdout.write("%s - %.2fs | " % (ret, delta.seconds + delta.microseconds/1E6))
        if binary_out:
            matches = read_output_matches_binary(tmp_fname)
        else:
            matches = read_output_matches(tmp_fname, has_num_matches)
    finally:
        # delete the output file if it exists
        try:
            os.remove(tmp_fname)
        except OSError:
            pass

    return matches
开发者ID:ahmadh84,项目名称:extern_sync,代码行数:25,代码来源:deepmatch_unittest.py


示例5: auto_resume

def auto_resume(cmd, logdir=os.curdir, name=None, logger=None, debug=True):
    if name is None:
        name = next(tempfile._get_candidate_names()) + '.log'

    logpath = os.path.join(logdir, name)

    if logger is None:
        logger = _init_default_logger(logpath, debug)

    if isinstance(cmd, list):
        cmd = ' '.join(cmd)

    while True:
        is_first_line = True
        for line in CommandRunner.run(cmd):
            if is_first_line:
                is_first_line = False
                logger.info('start `%s`'%cmd)

            if line.extra_attrs['tag'] is CommandRunner.Status.STDOUT:
                logger.debug(line)
            else:
                logger.warning(line)

        logger.error('found %s exit...'%cmd)
开发者ID:minghu6,项目名称:minghu6_py,代码行数:25,代码来源:cmd.py


示例6: abstracts

def abstracts(queryString):
	
# First call pubmed to pull out abstracts - one line per abstract	
    temp_name = "./"+next(tempfile._get_candidate_names())
    efetchCommand = "esearch -db pubmed -query \""+queryString+"\" | efetch -mode xml -format abstract | xtract -pattern PubmedArticle -block Abstract -element AbstractText>"+temp_name
    os.system(efetchCommand) 
	
# Now call Normalizr (Python 3 - oi vey) to normalise text. 
# Normalised text will overwrite original text.

    normalizeCommand = "/Users/upac004/Python/GOFind-master/normText.py "+ temp_name
    os.system(normalizeCommand)
    
# Now read in file to get each abstract and return a list    	
    theAbstracts = []
    fd = open(temp_name)
    for line in fd:

        
# Remove any special non-ASCII characters
        line = ''.join([i if ord(i) < 128 else '' for i in line]) 
        theAbstracts.append(line)
        
		
    fd.close()	
    os.remove(temp_name)

    return theAbstracts
开发者ID:hughshanahan,项目名称:GOFind,代码行数:28,代码来源:pubmedQuery.py


示例7: report_worker

def report_worker(sid):
    try:
        job = get_job(sid) 

        log.info("=============  STARTING WORKER  ==============")
        log.debug(job)
        from ast import literal_eval
        job['series'] = literal_eval(job['series'])  # From string
        # Expand paths to full location on filesystem 
        output_filename = os.path.join(
            app.config['UPLOAD_FOLDER'], 
            next(tempfile._get_candidate_names()) + '.pdf')

        # Make list of input datafiles
        input_datafiles = [
            os.path.join(app.config['UPLOAD_FOLDER'], f['temporary_name'])
            for f in get_files(sid)
        ]

        report.report(input_datafiles, output_filename, 
                      **{**job, 'pdf': True, 'htm': False})

        log.info("=============  WORKER FINISHED  ==============")

        # Update finished job 
        upd_job(sid, 'generated_pdf', output_filename)
        upd_job(sid, 'status', 'done')

    except Exception as e:
        log.error("Exception occurred in worker thread")
        log.error(sys.exc_info()[0])

        upd_job(sid, 'status', 'error')
        upd_job(sid, 'generated_pdf', None)
        raise e
开发者ID:sjmf,项目名称:reportgen,代码行数:35,代码来源:server.py


示例8: get_temp_aln

def get_temp_aln(aln):
    tfname = os.path.join(tempfile._get_default_tempdir(),
                          next(tempfile._get_candidate_names()))
    aln.write(tfname,alignment_format='PIR')
    seqs = get_seqs_from_pir(tfname)
    os.unlink(tfname)
    return seqs
开发者ID:integrativemodeling,项目名称:gamma-tusc,代码行数:7,代码来源:test_insertion_removal.py


示例9: random_names

def random_names(prefix, suffix=""):
    """Use the same technique that tempfile uses."""

    names = tempfile._get_candidate_names()

    for i in range(TMP_MAX):
        yield prefix + names.next() + suffix
开发者ID:utsdab,项目名称:usr,代码行数:7,代码来源:uniquefile.py


示例10: insert_qr

def insert_qr(pdf, x, y, code=1234567):
    if len(code) > 8: return;
    qr = qrcode.QRCode(
        version=2,
        error_correction=qrcode.constants.ERROR_CORRECT_M,
        box_size=10,
        border=2,
    )
    qr.add_data(HERBURL % code)
    qr.make(fit=True)
    img = qr.make_image()
    temp_name = os.path.join(BASE_URL, './tmp',
                             next(tempfile._get_candidate_names()))
    temp_name += '.png'
    try:
        with open(temp_name, 'w') as tmpfile:
            img.save(tmpfile)
            tmpfile.flush()
            pdf.set_xy(x + LABEL_WIDTH - QR_SIZE - 2, y + LABEL_HEIGHT - QR_SIZE - 4)
            pdf.image(temp_name, w=QR_SIZE, h=QR_SIZE)
    finally:
        try:
            os.remove(temp_name)
        except IOError:
            pass
开发者ID:scidam,项目名称:herbs,代码行数:25,代码来源:hlabel.py


示例11: run

    def run(self, musicbrainzid, fpath):
        temp_name = next(tempfile._get_candidate_names())
        tmpfile = "/tmp/%s.ly" % temp_name

        server_name = socket.gethostname()
        call(["/mnt/compmusic/%s/lilypond/usr/bin/musicxml2ly" % server_name, "--no-page-layout", fpath, "-o", tmpfile])

        tmp_dir = tempfile.mkdtemp()
        call(["lilypond", '-dpaper-size=\"junior-legal\"', "-dbackend=svg", "-o" "%s" % (tmp_dir), tmpfile])

        ret = {'score': []}

        os.unlink(tmpfile)

        regex = re.compile(r'.*<a style="(.*)" xlink:href="textedit:\/\/\/.*:([0-9]+):([0-9]+):([0-9]+)">.*')
        files = [os.path.join(tmp_dir, f) for f in os.listdir(tmp_dir)]
        files = filter(os.path.isfile, files)
        files.sort(key=lambda x: os.path.getmtime(x))

        for f in files:
            if f.endswith('.svg'):
                svg_file = open(f)
                score = svg_file.read()
                ret['score'].append(regex.sub(r'<a style="\1" id="l\2-f\3-t\4" from="\3" to="\4">', score))
                svg_file.close()
                os.remove(f)
        os.rmdir(tmp_dir)
        return ret
开发者ID:MTG,项目名称:pycompmusic,代码行数:28,代码来源:musicxml2svg.py


示例12: generateTemporaryName

 def generateTemporaryName(self):
     foundFileName = False
     while not (foundFileName):
         temporaryFileName = next(tempfile._get_candidate_names()) + ".txt"
         if not (os.path.isfile(temporaryFileName)):
             foundFileName = True
     return temporaryFileName
开发者ID:xzw0005,项目名称:SoftwareProcess,代码行数:7,代码来源:MonitorTest.py


示例13: gen_args

def gen_args ( args, infile_path, outfile ) :
    """
    Return the argument list generated from 'args' and the infile path
    requested.

    Arguments :
        args  ( string )
            Keyword or arguments to use in the call of Consense, excluding
            infile and outfile arguments.
        infile_path  ( string )
            Input alignment file path.
        outfile  ( string )
            Consensus tree output file.

    Returns :
        list
            List of arguments (excluding binary file) to call Consense.
    """
    if ( outfile ) :
        outfile_path = get_abspath(outfile)
    else :
        # Output files will be saved in temporary files to retrieve the
        # consensus tree
        outfile_path = os.path.join(tempfile.gettempdir(),
                                    tempfile.gettempprefix() + \
                                        next(tempfile._get_candidate_names()))
    # Create full command line list
    argument_list = [infile_path, outfile_path]
    return ( argument_list )
开发者ID:JAlvarezJarreta,项目名称:MEvoLib,代码行数:29,代码来源:_Consense.py


示例14: mode_pre

def mode_pre(session_dir, args):
    global gtmpfilename

    """
    Read from Session file and write to session.pre file
    """
    endtime_to_update = int(time.time()) - get_changelog_rollover_time(
        args.volume)
    status_file = os.path.join(session_dir, args.volume, "status")
    status_file_pre = status_file + ".pre"

    mkdirp(os.path.dirname(args.outfile), exit_on_err=True, logger=logger)

    # If Pre status file exists and running pre command again
    if os.path.exists(status_file_pre) and not args.regenerate_outfile:
        fail("Post command is not run after last pre, "
             "use --regenerate-outfile")

    start = 0
    try:
        with open(status_file) as f:
            start = int(f.read().strip())
    except ValueError:
        pass
    except (OSError, IOError) as e:
        fail("Error Opening Session file %s: %s"
             % (status_file, e), logger=logger)

    logger.debug("Pre is called - Session: %s, Volume: %s, "
                 "Start time: %s, End time: %s"
                 % (args.session, args.volume, start, endtime_to_update))

    prefix = datetime.now().strftime("%Y%m%d-%H%M%S-%f-")
    gtmpfilename = prefix + next(tempfile._get_candidate_names())

    run_cmd_nodes("pre", args, start=start, end=-1, tmpfilename=gtmpfilename)

    # Merger
    if args.full:
        cmd = ["sort", "-u"] + node_outfiles + ["-o", args.outfile]
        execute(cmd,
                exit_msg="Failed to merge output files "
                "collected from nodes", logger=logger)
    else:
        # Read each Changelogs db and generate finaldb
        create_file(args.outfile, exit_on_err=True, logger=logger)
        outfilemerger = OutputMerger(args.outfile + ".db", node_outfiles)
        write_output(args.outfile, outfilemerger, args.field_separator)

    try:
        os.remove(args.outfile + ".db")
    except (IOError, OSError):
        pass

    run_cmd_nodes("cleanup", args, tmpfilename=gtmpfilename)

    with open(status_file_pre, "w", buffering=0) as f:
        f.write(str(endtime_to_update))

    sys.stdout.write("Generated output file %s\n" % args.outfile)
开发者ID:raghavendrabhat,项目名称:glusterfs,代码行数:60,代码来源:main.py


示例15: do_upload_cap

	def do_upload_cap(s):
		cl = int(s.headers['Content-Length'])
		tmp_cap = "/tmp/" + next(tempfile._get_candidate_names()) + ".cap"
		with open(tmp_cap + ".gz", "wb") as fid:
			fid.write(s.rfile.read(cl))

		decompress(tmp_cap)
        
		# Check file is valid
		output = subprocess.check_output(['wpaclean', tmp_cap + ".tmp", tmp_cap])
		try:
			os.remove(tmp_cap + ".tmp")
		except:
			pass

		output_split = output.splitlines()
		if len(output_split) > 2:
			# We got more than 2 lines, which means there is a network
			#  in there with a WPA/2 PSK handshake
			os.rename(tmp_cap + ".gz", "dcrack.cap.gz")
			os.rename(tmp_cap, "dcrack.cap")
		else:
			 # If nothing in the file, just delete it
			os.remove(tmp_cap)
			os.remove(tmp_cap + ".gz")
开发者ID:JoeGilkey,项目名称:carnivore,代码行数:25,代码来源:dcrack.py


示例16: generate_temp_filename

def generate_temp_filename(dirname=None, prefix='tmp', suffix=''):
    """Generate a temporary file name with specified suffix and prefix.

    >>> from stonemason.util.tempfn import generate_temp_filename
    >>> generate_temp_filename('/tmp', prefix='hello-', suffix='.tmp') #doctest: +ELLIPSIS
    '/tmp/hello-....tmp'

    :param dirname: Base temp directory, default is system temp dir.
    :type dirname: str
    :param prefix: Prefix of the temporary file name, default is ``tmp``
    :type prefix: str
    :param suffix: Suffix of the temporary file name, default is emptry string.
    :type suffix: str
    :return: Generated temporary file name.
    :rtype: str
    :raises: :class:`IOError`
    """
    assert isinstance(suffix, six.string_types)
    assert isinstance(prefix, six.string_types)

    if not dirname:
        dirname = os.path.join(tempfile.gettempdir(), STONEMASON_TEMP_ROOT)
        if not os.path.exists(dirname):
            os.mkdir(dirname)

    for n, temp in enumerate(tempfile._get_candidate_names()):
        basename = '%s%s%s' % (prefix, temp, suffix)
        return os.path.join(dirname, basename)

    raise IOError(errno.EEXIST, 'Exhausted temporary file names.')
开发者ID:Kotaimen,项目名称:stonemason,代码行数:30,代码来源:tempfn.py


示例17: save_flask_file_to_temp_from_req

 def save_flask_file_to_temp_from_req(filename, flask_files):
     if filename in flask_files and flask_files[filename].filename:
         uploaded_file = flask_files[filename]
         temp_file = "/tmp/" + next(tempfile._get_candidate_names()) + FileUtil.get_ext_with_dot(
             uploaded_file.filename)
         uploaded_file.save(temp_file)
         return temp_file
开发者ID:govind1246,项目名称:python-flask-dokku-app,代码行数:7,代码来源:common.py


示例18: get_tempname

def get_tempname():
    """
    Gets a random string for use as a temporary filename.

    :return: A filename that can be used.
    """
    return next(tempfile._get_candidate_names())
开发者ID:chintal,项目名称:tendril,代码行数:7,代码来源:fsutils.py


示例19: create_appliance

def create_appliance(args):
    """Convert disk to another format."""
    input_ = op.abspath(to_unicode(args.input))
    output = op.abspath(to_unicode(args.output))
    temp_filename = to_unicode(next(tempfile._get_candidate_names()))
    temp_file = op.abspath(to_unicode(".%s" % temp_filename))
    output_fmt = args.format.lower()
    output_filename = "%s.%s" % (output, output_fmt)

    os.environ['LIBGUESTFS_CACHEDIR'] = os.getcwd()
    if args.verbose:
        os.environ['LIBGUESTFS_DEBUG'] = '1'

    create_disk(input_,
                temp_file,
                args.format,
                args.size,
                args.filesystem,
                args.verbose)
    logger.info("Installing bootloader")
    uuid, _, _ = install_bootloader(temp_file,
                                    args.extlinux_mbr,
                                    args.append)
    generate_fstab(temp_file, uuid, args.filesystem)

    logger.info("Exporting appliance to %s" % output_filename)
    if output_fmt == "qcow2":
        shutil.move(temp_file, output_filename)
    else:
        qemu_convert(temp_file, output_fmt, output_filename)
        os.remove(temp_file) if os.path.exists(temp_file) else None
开发者ID:mickours,项目名称:kameleon-helpers,代码行数:31,代码来源:create_appliance.py


示例20: prepare_queue

def prepare_queue(options):
    """Prepare a file which holds all hosts (targets) to scan."""
    expanded = False
    try:
        if not options['inputfile']:
            expanded = next(tempfile._get_candidate_names())  # pylint: disable=protected-access
            with open(expanded, 'a') as inputfile:
                inputfile.write(options['target'])
                options['inputfile'] = expanded
        with open(options['inputfile'], 'r') as inputfile:
            targets = []
            for host in [line for line in inputfile.read().splitlines() if line.strip()]:
                if options['dry_run'] or not re.match(r'.*[\.:].*[-/][0-9]+', host):
                    targets.append(host)
                else:
                    arguments = '-nsL'
                    scanner = nmap.PortScanner()
                    scanner.scan(hosts='{0}'.format(host), arguments=arguments)
                    if '.' in scanner.all_hosts():
                        targets += sorted(scanner.all_hosts(),
                                          key=lambda x: tuple(map(int, x.split('.'))))
                    else:
                        targets += scanner.all_hosts()
            with open(options['queuefile'], 'a') as queuefile:
                for target in targets:
                    queuefile.write(target + '\n')
        if expanded:
            os.remove(expanded)
    except IOError as exception:
        abort_program('Could not read/write file: {0}'.format(exception))
开发者ID:PeterMosmans,项目名称:security-scripts,代码行数:30,代码来源:analyze_hosts.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python tempfile._get_default_tempdir函数代码示例发布时间:2022-05-27
下一篇:
Python tempfile._candidate_tempdir_list函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap