Python tempfile.mktemp() Examples

The following are 30 code examples of tempfile.mktemp(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tempfile , or try the search function .
Example #1
Source File: test_local.py    From py with MIT License 7 votes vote down vote up
def test_setmtime(self):
        import tempfile
        import time
        try:
            fd, name = tempfile.mkstemp()
            os.close(fd)
        except AttributeError:
            name = tempfile.mktemp()
            open(name, 'w').close()
        try:
            mtime = int(time.time())-100
            path = local(name)
            assert path.mtime() != mtime
            path.setmtime(mtime)
            assert path.mtime() == mtime
            path.setmtime()
            assert path.mtime() != mtime
        finally:
            os.remove(name) 
Example #2
Source File: test_format.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_version_2_0_memmap():
    # requires more than 2 byte for header
    dt = [(("%d" % i) * 100, float) for i in range(500)]
    d = np.ones(1000, dtype=dt)
    tf = tempfile.mktemp('', 'mmap', dir=tempdir)

    # 1.0 requested but data cannot be saved this way
    assert_raises(ValueError, format.open_memmap, tf, mode='w+', dtype=d.dtype,
                            shape=d.shape, version=(1, 0))

    ma = format.open_memmap(tf, mode='w+', dtype=d.dtype,
                            shape=d.shape, version=(2, 0))
    ma[...] = d
    del ma

    with warnings.catch_warnings(record=True) as w:
        warnings.filterwarnings('always', '', UserWarning)
        ma = format.open_memmap(tf, mode='w+', dtype=d.dtype,
                                shape=d.shape, version=None)
        assert_(w[0].category is UserWarning)
        ma[...] = d
        del ma

    ma = format.open_memmap(tf, mode='r')
    assert_array_equal(ma, d) 
Example #3
Source File: goldstandardassembly.py    From CAMISIM with Apache License 2.0 6 votes vote down vote up
def pooled_gold_standard_by_dir(self, list_of_directory_bam, dict_id_to_file_path_fasta, file_path_output=None):
        """
            Make a gold standard assembly merging bam files of several samples

            @attention: bam files must have same name to be merged

            @param list_of_directory_bam: list of directories containing bam files
            @type list_of_directory_bam: list[str|unicode]
            @param dict_id_to_file_path_fasta: path to reference files by key
            @type dict_id_to_file_path_fasta: dict[str|unicode, str|unicode]

            @return: output file path
            @rtype: str | unicode
        """
        if file_path_output is None:
            file_path_output = tempfile.mktemp(dir=self._tmp_dir)
        self._logger.info("Creating pooled gold standard")
        self.merge_bam_files_by_list_of_dir(list_of_directory_bam, output_dir=self._temp_merges_bam_directory)
        dict_id_to_file_path_bam = self.get_dict_id_to_file_path_bam_from_dir(self._temp_merges_bam_directory)
        return self.gold_standard_assembly(dict_id_to_file_path_bam, dict_id_to_file_path_fasta, file_path_output) 
Example #4
Source File: test_recordio.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def test_recordio():
    frec = tempfile.mktemp()
    N = 255

    writer = mx.recordio.MXRecordIO(frec, 'w')
    for i in range(N):
        if sys.version_info[0] < 3:
            writer.write(str(chr(i)))
        else:
            writer.write(bytes(str(chr(i)), 'utf-8'))
    del writer

    reader = mx.recordio.MXRecordIO(frec, 'r')
    for i in range(N):
        res = reader.read()
        if sys.version_info[0] < 3:
            assert res == str(chr(i))
        else:
            assert res == bytes(str(chr(i)), 'utf-8') 
Example #5
Source File: test_recordio.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def test_indexed_recordio():
    fidx = tempfile.mktemp()
    frec = tempfile.mktemp()
    N = 255

    writer = mx.recordio.MXIndexedRecordIO(fidx, frec, 'w')
    for i in range(N):
        if sys.version_info[0] < 3:
            writer.write_idx(i, str(chr(i)))
        else:
            writer.write_idx(i, bytes(str(chr(i)), 'utf-8'))
    del writer

    reader = mx.recordio.MXIndexedRecordIO(fidx, frec, 'r')
    keys = reader.keys
    assert sorted(keys) == [i for i in range(N)]
    random.shuffle(keys)
    for i in keys:
        res = reader.read_idx(i)
        if sys.version_info[0] < 3:
            assert res == str(chr(i))
        else:
            assert res == bytes(str(chr(i)), 'utf-8') 
Example #6
Source File: test_format.py    From lambda-packs with MIT License 6 votes vote down vote up
def test_version_2_0_memmap():
    # requires more than 2 byte for header
    dt = [(("%d" % i) * 100, float) for i in range(500)]
    d = np.ones(1000, dtype=dt)
    tf = tempfile.mktemp('', 'mmap', dir=tempdir)

    # 1.0 requested but data cannot be saved this way
    assert_raises(ValueError, format.open_memmap, tf, mode='w+', dtype=d.dtype,
                            shape=d.shape, version=(1, 0))

    ma = format.open_memmap(tf, mode='w+', dtype=d.dtype,
                            shape=d.shape, version=(2, 0))
    ma[...] = d
    del ma

    with warnings.catch_warnings(record=True) as w:
        warnings.filterwarnings('always', '', UserWarning)
        ma = format.open_memmap(tf, mode='w+', dtype=d.dtype,
                                shape=d.shape, version=None)
        assert_(w[0].category is UserWarning)
        ma[...] = d
        del ma

    ma = format.open_memmap(tf, mode='r')
    assert_array_equal(ma, d) 
Example #7
Source File: request.py    From anime-downloader with The Unlicense 6 votes vote down vote up
def _log_response_body(res):
    import json
    import pathlib
    file = tempfile.mktemp(dir=temp_dir)
    logger.debug(file)
    with open(file, 'w', encoding="utf-8") as f:
        f.write(res.text)

    data_file = temp_dir + '/data.json'
    if not os.path.exists(data_file):
        with open(data_file, 'w') as f:
            json.dump([], f)
    data = None
    with open(data_file, 'r') as f:
        data = json.load(f)
        data.append({
            'method': res.request.method,
            'url': res.url,
            'file': pathlib.Path(file).name,
        })
    with open(data_file, 'w') as f:
        json.dump(data, f) 
Example #8
Source File: shci.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def SHCISCF(mf, norb, nelec, maxM=1000, tol=1.0e-8, *args, **kwargs):
    """Shortcut function to setup CASSCF using the SHCI solver.  The SHCI
    solver is properly initialized in this function so that the 1-step
    algorithm can applied with SHCI-CASSCF.

    Examples:

    >>> mol = gto.M(atom='C 0 0 0; C 0 0 1')
    >>> mf = scf.RHF(mol).run()
    >>> mc = SHCISCF(mf, 4, 4)
    >>> mc.kernel()
    -74.414908818611522
    """

    mc = mcscf.CASSCF(mf, norb, nelec, *args, **kwargs)
    mc.fcisolver = SHCI(mf.mol, maxM, tol=tol)
    # mc.callback = mc.fcisolver.restart_scheduler_() #TODO
    if mc.chkfile == mc._scf._chkfile.name:
        # Do not delete chkfile after mcscf
        mc.chkfile = tempfile.mktemp(dir=settings.SHCISCRATCHDIR)
        if not os.path.exists(settings.SHCISCRATCHDIR):
            os.makedirs(settings.SHCISCRATCHDIR)
    return mc 
Example #9
Source File: shci.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def SHCISCF(mf, norb, nelec, maxM=1000, tol=1.0e-8, *args, **kwargs):
    """Shortcut function to setup CASSCF using the SHCI solver.  The SHCI
    solver is properly initialized in this function so that the 1-step
    algorithm can applied with SHCI-CASSCF.

    Examples:

    >>> mol = gto.M(atom='C 0 0 0; C 0 0 1')
    >>> mf = scf.RHF(mol).run()
    >>> mc = SHCISCF(mf, 4, 4)
    >>> mc.kernel()
    -74.414908818611522
    """

    mc = mcscf.CASSCF(mf, norb, nelec, *args, **kwargs)
    mc.fcisolver = SHCI(mf.mol, maxM, tol=tol)
    # mc.callback = mc.fcisolver.restart_scheduler_() #TODO
    if mc.chkfile == mc._scf._chkfile.name:
        # Do not delete chkfile after mcscf
        mc.chkfile = tempfile.mktemp(dir=settings.SHCISCRATCHDIR)
        if not os.path.exists(settings.SHCISCRATCHDIR):
            os.makedirs(settings.SHCISCRATCHDIR)
    return mc 
Example #10
Source File: dmrgci.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def DMRGSCF(mf, norb, nelec, maxM=1000, tol=1.e-8, *args, **kwargs):
    '''Shortcut function to setup CASSCF using the DMRG solver.  The DMRG
    solver is properly initialized in this function so that the 1-step
    algorithm can be applied with DMRG-CASSCF.

    Examples:

    >>> mol = gto.M(atom='C 0 0 0; C 0 0 1')
    >>> mf = scf.RHF(mol).run()
    >>> mc = DMRGSCF(mf, 4, 4)
    >>> mc.kernel()
    -74.414908818611522
    '''
    if getattr(mf, 'with_df', None):
        mc = mcscf.DFCASSCF(mf, norb, nelec, *args, **kwargs)
    else:
        mc = mcscf.CASSCF(mf, norb, nelec, *args, **kwargs)
    mc.fcisolver = DMRGCI(mf.mol, maxM, tol=tol)
    mc.callback = mc.fcisolver.restart_scheduler_()
    if mc.chkfile == mc._scf._chkfile.name:
        # Do not delete chkfile after mcscf
        mc.chkfile = tempfile.mktemp(dir=settings.BLOCKSCRATCHDIR)
        if not os.path.exists(settings.BLOCKSCRATCHDIR):
            os.makedirs(settings.BLOCKSCRATCHDIR)
    return mc 
Example #11
Source File: dmrgci.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def DMRGSCF(mf, norb, nelec, maxM=1000, tol=1.e-8, *args, **kwargs):
    '''Shortcut function to setup CASSCF using the DMRG solver.  The DMRG
    solver is properly initialized in this function so that the 1-step
    algorithm can be applied with DMRG-CASSCF.

    Examples:

    >>> mol = gto.M(atom='C 0 0 0; C 0 0 1')
    >>> mf = scf.RHF(mol).run()
    >>> mc = DMRGSCF(mf, 4, 4)
    >>> mc.kernel()
    -74.414908818611522
    '''
    if getattr(mf, 'with_df', None):
        mc = mcscf.DFCASSCF(mf, norb, nelec, *args, **kwargs)
    else:
        mc = mcscf.CASSCF(mf, norb, nelec, *args, **kwargs)
    mc.fcisolver = DMRGCI(mf.mol, maxM, tol=tol)
    mc.callback = mc.fcisolver.restart_scheduler_()
    if mc.chkfile == mc._scf._chkfile.name:
        # Do not delete chkfile after mcscf
        mc.chkfile = tempfile.mktemp(dir=settings.BLOCKSCRATCHDIR)
        if not os.path.exists(settings.BLOCKSCRATCHDIR):
            os.makedirs(settings.BLOCKSCRATCHDIR)
    return mc 
Example #12
Source File: test_node_operations.py    From me-ica with GNU Lesser General Public License v2.1 6 votes vote down vote up
def test_Node_save():
    test_list = [1,2,3]
    generic_node = mdp.Node()
    generic_node.dummy_attr = test_list
    # test string save
    copy_node_pic = generic_node.save(None)
    copy_node = cPickle.loads(copy_node_pic)
    assert generic_node.dummy_attr == copy_node.dummy_attr,\
           'Node save (string) method did not work'
    copy_node.dummy_attr[0] = 10
    assert generic_node.dummy_attr != copy_node.dummy_attr,\
           'Node save (string) method did not work'
    # test file save
    dummy_file = tempfile.mktemp(prefix='MDP_', suffix=".pic",
                                 dir=py.test.mdp_tempdirname)
    generic_node.save(dummy_file, protocol=1)
    dummy_file = open(dummy_file, 'rb')
    copy_node = cPickle.load(dummy_file)
    assert generic_node.dummy_attr == copy_node.dummy_attr,\
           'Node save (file) method did not work'
    copy_node.dummy_attr[0] = 10
    assert generic_node.dummy_attr != copy_node.dummy_attr,\
           'Node save (file) method did not work' 
Example #13
Source File: test_win32file.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        self.watcher_threads = []
        self.watcher_thread_changes = []
        self.dir_names = []
        self.dir_handles = []
        for i in range(self.num_test_dirs):
            td = tempfile.mktemp("-test-directory-changes-%d" % i)
            os.mkdir(td)
            self.dir_names.append(td)
            hdir = win32file.CreateFile(td, 
                                        ntsecuritycon.FILE_LIST_DIRECTORY,
                                        win32con.FILE_SHARE_READ,
                                        None, # security desc
                                        win32con.OPEN_EXISTING,
                                        win32con.FILE_FLAG_BACKUP_SEMANTICS |
                                        win32con.FILE_FLAG_OVERLAPPED,
                                        None)
            self.dir_handles.append(hdir)

            changes = []
            t = threading.Thread(target=self._watcherThreadOverlapped,
                                 args=(td, hdir, changes))
            t.start()
            self.watcher_threads.append(t)
            self.watcher_thread_changes.append(changes) 
Example #14
Source File: test_pybase16.py    From base16-builder-python with MIT License 6 votes vote down vote up
def test_custom_build(clean_dir):
    """Test building with specific parameters."""
    dunst_temp_path = shared.rel_to_cwd('templates', 'dunst')
    base_output_dir = tempfile.mktemp()
    builder.build(templates=[dunst_temp_path], schemes=['atelier-heath-light'],
                  base_output_dir=base_output_dir)

    dunst_temps = builder.TemplateGroup(dunst_temp_path).get_templates()
    # out_dirs = [dunst_temps[temp]['output'] for temp in dunst_temps.keys()]
    for temp, sub in dunst_temps.items():
        out_path = os.path.join(base_output_dir, 'dunst',
                                sub['output'])
        theme_file = 'base16-atelier-heath-light{}'.format(sub['extension'])
        out_file = os.path.join(out_path, theme_file)

        assert os.path.exists(out_file)
        assert len(os.listdir(out_path)) == 1 
Example #15
Source File: test_exit_crash.py    From tf-pose with Apache License 2.0 6 votes vote down vote up
def test_exit_crash():
    # For each Widget subclass, run a simple python script that creates an
    # instance and then shuts down. The intent is to check for segmentation
    # faults when each script exits.
    tmp = tempfile.mktemp(".py")
    path = os.path.dirname(pg.__file__)

    initArgs = {
        'CheckTable': "[]",
        'ProgressDialog': '"msg"',
        'VerticalLabel': '"msg"',
    }

    for name in dir(pg):
        obj = getattr(pg, name)
        if not isinstance(obj, type) or not issubclass(obj, pg.QtGui.QWidget):
            continue

        print(name)
        argstr = initArgs.get(name, "")
        open(tmp, 'w').write(code.format(path=path, classname=name, args=argstr))
        proc = subprocess.Popen([sys.executable, tmp])
        assert proc.wait() == 0

    os.remove(tmp) 
Example #16
Source File: userscripts.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def prepare_run(self, *args, **kwargs):
        self._args = args
        self._kwargs = kwargs

        try:
            # tempfile.mktemp is deprecated and discouraged, but we use it here
            # to create a FIFO since the only other alternative would be to
            # create a directory and place the FIFO there, which sucks. Since
            # os.mkfifo will raise an exception anyways when the path doesn't
            # exist, it shouldn't be a big issue.
            self._filepath = tempfile.mktemp(prefix='qutebrowser-userscript-',
                                             dir=standarddir.runtime())
            # pylint: disable=no-member,useless-suppression
            os.mkfifo(self._filepath, mode=0o600)
            # pylint: enable=no-member,useless-suppression
        except OSError as e:
            self._filepath = None  # Make sure it's not used
            message.error("Error while creating FIFO: {}".format(e))
            return

        self._reader = _QtFIFOReader(self._filepath)
        self._reader.got_line.connect(self.got_cmd)  # type: ignore[arg-type] 
Example #17
Source File: cgc_exploit_factory.py    From rex with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def generate_report(self, register_setters, leakers):

        stat_name = tempfile.mktemp(dir=".", prefix='rex-results-')

        l.info("exploitation report being written to '%s'", stat_name)

        f = open(stat_name, 'w')
        f.write("Binary %s:\n" % os.path.basename(self.crash.project.filename))
        f.write("Register setting exploits:\n")
        for register_setter in register_setters:
            f.write("\t%s\n" % str(register_setter))
        f.write("\n")
        f.write("Leaker exploits:\n")
        for leaker in leakers:
            f.write("\t%s\n" % str(leaker))

        f.close() 
Example #18
Source File: cgc_exploit.py    From rex with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_binary(self, enable_randomness=True, times=1, timeout=15):
        """
        Test the binary generated
        """

        # dump the binary code
        pov_binary_filename = tempfile.mktemp(dir='/tmp', prefix='rex-pov-')
        self.dump_binary(filename=pov_binary_filename)
        os.chmod(pov_binary_filename, 0o755)

        pov_tester = CGCPovSimulator()
        result = pov_tester.test_binary_pov(
                pov_binary_filename,
                self.crash.binary,
                enable_randomness=enable_randomness,
                timeout=timeout,
                times=times)

        # remove the generated pov
        os.remove(pov_binary_filename)

        return result 
Example #19
Source File: test_cli.py    From covimerage with MIT License 6 votes vote down vote up
def test_cli_writecoverage_source(runner, devnull):
    from covimerage.coveragepy import CoverageWrapper

    fname = tempfile.mktemp()
    result = runner.invoke(cli.main, [
        'write_coverage', '--data-file', fname, '--source', '.',
        'tests/fixtures/conditional_function.profile'])
    assert result.output == '\n'.join([
        'Writing coverage file %s.' % fname,
        ''])
    assert result.exit_code == 0

    cov = CoverageWrapper(data_file=fname)
    assert cov.lines[
        os.path.abspath('tests/test_plugin/conditional_function.vim')] == [
            3, 8, 9, 11, 13, 14, 15, 17, 23]
    assert cov.lines[
        os.path.abspath('tests/test_plugin/autoload/test_plugin.vim')] == [] 
Example #20
Source File: test_flows.py    From me-ica with GNU Lesser General Public License v2.1 6 votes vote down vote up
def testFlow_save():
    dummy_list = [1,2,3]
    flow = _get_default_flow()
    flow[0].dummy_attr = dummy_list
    # test string save
    copy_flow_pic = flow.save(None)
    copy_flow = cPickle.loads(copy_flow_pic)
    assert flow[0].dummy_attr == copy_flow[0].dummy_attr, \
           'Flow save (string) method did not work'
    copy_flow[0].dummy_attr[0] = 10
    assert flow[0].dummy_attr != copy_flow[0].dummy_attr, \
           'Flow save (string) method did not work'
    # test file save
    dummy_file = tempfile.mktemp(prefix='MDP_', suffix=".pic",
                                 dir=py.test.mdp_tempdirname)
    flow.save(dummy_file, protocol=1)
    dummy_file = open(dummy_file, 'rb')
    copy_flow = cPickle.load(dummy_file)
    assert flow[0].dummy_attr == copy_flow[0].dummy_attr, \
           'Flow save (file) method did not work'
    copy_flow[0].dummy_attr[0] = 10
    assert flow[0].dummy_attr != copy_flow[0].dummy_attr, \
           'Flow save (file) method did not work' 
Example #21
Source File: solvers.py    From MatchingMarkets.py with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def callSolver(self, lp, callback = None):
            """Solves the problem with yaposib
            """
            if self.msg == 0:
                #close stdout to get rid of messages
                tempfile = open(mktemp(),'w')
                savestdout = os.dup(1)
                os.close(1)
                if os.dup(tempfile.fileno()) != 1:
                    raise PulpSolverError("couldn't redirect stdout - dup() error")
            self.solveTime = -clock()
            lp.solverModel.solve(self.mip)
            self.solveTime += clock()
            if self.msg == 0:
                #reopen stdout
                os.close(1)
                os.dup(savestdout)
                os.close(savestdout) 
Example #22
Source File: test_dumper.py    From rucio with Apache License 2.0 5 votes vote down vote up
def test_temp_file_cleanup_on_exception_with_final_name():
    final_name = tempfile.mktemp()
    try:
        with dumper.temp_file('/tmp', final_name) as (_, tmp_path):
            tmp_path = os.path.join('/tmp', tmp_path)
            raise Exception
    except:
        pass
    finally:
        ok_(not os.path.exists(tmp_path), tmp_path)
        ok_(not os.path.exists(final_name), final_name) 
Example #23
Source File: test_win32rcparser.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        # don't call base!
        rc_file = os.path.join(os.path.dirname(__file__), "win32rcparser", "test.rc")
        py_file = tempfile.mktemp('test_win32rcparser.py')
        try:
            win32rcparser.GenerateFrozenResource(rc_file, py_file)
            py_source = open(py_file).read()
        finally:
            if os.path.isfile(py_file):
                os.unlink(py_file)
            
        # poor-man's import :)
        globs = {}
        exec py_source in globs, globs
        self.resources = globs["FakeParser"]() 
Example #24
Source File: test_proxies.py    From earthengine with MIT License 5 votes vote down vote up
def setUp(self):
        if not socks:
            raise nose.SkipTest('socks module unavailable')
        if not subprocess:
            raise nose.SkipTest('subprocess module unavailable')

        # start a short-lived miniserver so we can get a likely port
        # for the proxy
        self.httpd, self.proxyport = miniserver.start_server(
            miniserver.ThisDirHandler)
        self.httpd.shutdown()
        self.httpd, self.port = miniserver.start_server(
            miniserver.ThisDirHandler)

        self.pidfile = tempfile.mktemp()
        self.logfile = tempfile.mktemp()
        fd, self.conffile = tempfile.mkstemp()
        f = os.fdopen(fd, 'w')
        our_cfg = tinyproxy_cfg % {'user': os.getlogin(),
                                   'pidfile': self.pidfile,
                                   'port': self.proxyport,
                                   'logfile': self.logfile}
        f.write(our_cfg)
        f.close()
        try:
            # TODO use subprocess.check_call when 2.4 is dropped
            ret = subprocess.call(['tinyproxy', '-c', self.conffile])
            self.assertEqual(0, ret)
        except OSError, e:
            if e.errno == errno.ENOENT:
                raise nose.SkipTest('tinyproxy not available')
            raise 
Example #25
Source File: test_win32file.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def testFileTimesTimezones(self):
        if not issubclass(pywintypes.TimeType, datetime.datetime):
            # maybe should report 'skipped', but that's not quite right as
            # there is nothing you can do to avoid it being skipped!
            return
        filename = tempfile.mktemp("-testFileTimes")
        now_utc = win32timezone.utcnow()
        now_local = now_utc.astimezone(win32timezone.TimeZoneInfo.local())
        h = win32file.CreateFile(filename,
                                 win32file.GENERIC_READ|win32file.GENERIC_WRITE,
                                 0, None, win32file.CREATE_ALWAYS, 0, 0)
        try:
            win32file.SetFileTime(h, now_utc, now_utc, now_utc)
            ct, at, wt = win32file.GetFileTime(h)
            self.failUnlessEqual(now_local, ct)
            self.failUnlessEqual(now_local, at)
            self.failUnlessEqual(now_local, wt)
            # and the reverse - set local, check against utc
            win32file.SetFileTime(h, now_local, now_local, now_local)
            ct, at, wt = win32file.GetFileTime(h)
            self.failUnlessEqual(now_utc, ct)
            self.failUnlessEqual(now_utc, at)
            self.failUnlessEqual(now_utc, wt)
        finally:
            h.close()
            os.unlink(filename) 
Example #26
Source File: doctest24.py    From mishkal with GNU General Public License v3.0 5 votes vote down vote up
def debug_script(src, pm=False, globs=None):
    "Debug a test script.  `src` is the script, as a string."
    import pdb

    # Note that tempfile.NameTemporaryFile() cannot be used.  As the
    # docs say, a file so created cannot be opened by name a second time
    # on modern Windows boxes, and execfile() needs to open it.
    srcfilename = tempfile.mktemp(".py", "doctestdebug")
    f = open(srcfilename, 'w')
    f.write(src)
    f.close()

    try:
        if globs:
            globs = globs.copy()
        else:
            globs = {}

        if pm:
            try:
                execfile(srcfilename, globs, globs)
            except:
                print sys.exc_info()[1]
                pdb.post_mortem(sys.exc_info()[2])
        else:
            # Note that %r is vital here.  '%s' instead can, e.g., cause
            # backslashes to get treated as metacharacters on Windows.
            pdb.run("execfile(%r)" % srcfilename, globs, globs)

    finally:
        os.remove(srcfilename) 
Example #27
Source File: cached.py    From filesystem_spec with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def save_cache(self):
        """Save set of stored blocks from file"""
        fn = os.path.join(self.storage[-1], "cache")
        # TODO: a file lock could be used to ensure file does not change
        #  between re-read and write; but occasional duplicated reads ok.
        cache = self.cached_files[-1]
        if os.path.exists(fn):
            with open(fn, "rb") as f:
                cached_files = pickle.load(f)
            for k, c in cached_files.items():
                if c["blocks"] is not True:
                    if cache[k]["blocks"] is True:
                        c["blocks"] = True
                    else:
                        c["blocks"] = set(c["blocks"]).union(cache[k]["blocks"])

            # Files can be added to cache after it was written once
            for k, c in cache.items():
                if k not in cached_files:
                    cached_files[k] = c
        else:
            cached_files = cache
        cache = {k: v.copy() for k, v in cached_files.items()}
        for c in cache.values():
            if isinstance(c["blocks"], set):
                c["blocks"] = list(c["blocks"])
        fn2 = tempfile.mktemp()
        with open(fn2, "wb") as f:
            pickle.dump(cache, f)
        os.makedirs(os.path.dirname(fn), exist_ok=True)
        move(fn2, fn) 
Example #28
Source File: cached.py    From filesystem_spec with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, fs, path, fn=None, mode="wb", autocommit=True, seek=0):
        fn = fn or tempfile.mktemp()
        self.mode = mode
        self.fn = fn
        self.fh = open(fn, mode)
        if seek:
            self.fh.seek(seek)
        self.path = path
        self.fs = fs
        self.closed = False
        self.autocommit = autocommit 
Example #29
Source File: test_dumper.py    From rucio with Apache License 2.0 5 votes vote down vote up
def test_temp_file_with_final_name_creates_a_tmp_file_and_then_removes_it():
    final_name = tempfile.mktemp()
    with dumper.temp_file('/tmp', final_name) as (_, tmp_path):
        tmp_path = os.path.join('/tmp', tmp_path)
        ok_(os.path.exists(tmp_path), tmp_path)
        ok_(not os.path.exists(final_name), tmp_path)

    ok_(os.path.exists(final_name), final_name)
    ok_(not os.path.exists(tmp_path), tmp_path)
    os.unlink(final_name) 
Example #30
Source File: _termui_impl.py    From jbox with MIT License 5 votes vote down vote up
def _tempfilepager(text, cmd, color):
    """Page through text by invoking a program on a temporary file."""
    import tempfile
    filename = tempfile.mktemp()
    if not color:
        text = strip_ansi(text)
    encoding = get_best_encoding(sys.stdout)
    with open_stream(filename, 'wb')[0] as f:
        f.write(text.encode(encoding))
    try:
        os.system(cmd + ' "' + filename + '"')
    finally:
        os.unlink(filename)