Python tempfile.mktemp() Examples

The following are code examples for showing how to use tempfile.mktemp(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_tempfile.py    GNU Lesser General Public License v3.0 7 votes vote down vote up
def test_exports(self):
        # There are no surprising symbols in the tempfile module
        dict = tempfile.__dict__

        expected = {
            "NamedTemporaryFile" : 1,
            "TemporaryFile" : 1,
            "mkstemp" : 1,
            "mkdtemp" : 1,
            "mktemp" : 1,
            "TMP_MAX" : 1,
            "gettempprefix" : 1,
            "gettempdir" : 1,
            "tempdir" : 1,
            "template" : 1,
            "SpooledTemporaryFile" : 1
        }

        unexp = []
        for key in dict:
            if key[0] != '_' and key not in expected:
                unexp.append(key)
        self.assertTrue(len(unexp) == 0,
                        "unexpected keys: %s" % unexp) 
Example 2
Project: pyblish-win   Author: pyblish   File: test_contextlib.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def testWithOpen(self):
        tfn = tempfile.mktemp()
        try:
            f = None
            with open(tfn, "w") as f:
                self.assertFalse(f.closed)
                f.write("Booh\n")
            self.assertTrue(f.closed)
            f = None
            with self.assertRaises(ZeroDivisionError):
                with open(tfn, "r") as f:
                    self.assertFalse(f.closed)
                    self.assertEqual(f.read(), "Booh\n")
                    1 // 0
            self.assertTrue(f.closed)
        finally:
            test_support.unlink(tfn) 
Example 3
Project: pyblish-win   Author: pyblish   File: test_defaultdict.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_print(self):
        d1 = defaultdict()
        def foo(): return 42
        d2 = defaultdict(foo, {1: 2})
        # NOTE: We can't use tempfile.[Named]TemporaryFile since this
        # code must exercise the tp_print C code, which only gets
        # invoked for *real* files.
        tfn = tempfile.mktemp()
        try:
            f = open(tfn, "w+")
            try:
                print >>f, d1
                print >>f, d2
                f.seek(0)
                self.assertEqual(f.readline(), repr(d1) + "\n")
                self.assertEqual(f.readline(), repr(d2) + "\n")
            finally:
                f.close()
        finally:
            os.remove(tfn) 
Example 4
Project: pyblish-win   Author: pyblish   File: test_defaultdict.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_recursive_repr(self):
        # Issue2045: stack overflow when default_factory is a bound method
        class sub(defaultdict):
            def __init__(self):
                self.default_factory = self._factory
            def _factory(self):
                return []
        d = sub()
        self.assertTrue(repr(d).startswith(
            "defaultdict(<bound method sub._factory of defaultdict(..."))

        # NOTE: printing a subclass of a builtin type does not call its
        # tp_print slot. So this part is essentially the same test as above.
        tfn = tempfile.mktemp()
        try:
            f = open(tfn, "w+")
            try:
                print >>f, d
            finally:
                f.close()
        finally:
            os.remove(tfn) 
Example 5
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_encoding_plain_file(self):
        # In Python 2.x, a plain file object is treated as having no encoding.
        log = logging.getLogger("test")
        fn = tempfile.mktemp(".log")
        # the non-ascii data we write to the log.
        data = "foo\x80"
        try:
            handler = logging.FileHandler(fn)
            log.addHandler(handler)
            try:
                # write non-ascii data to the log.
                log.warning(data)
            finally:
                log.removeHandler(handler)
                handler.close()
            # check we wrote exactly those bytes, ignoring trailing \n etc
            f = open(fn)
            try:
                self.assertEqual(f.read().rstrip(), data)
            finally:
                f.close()
        finally:
            if os.path.isfile(fn):
                os.remove(fn) 
Example 6
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: test_recordio.py    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 7
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: test_recordio.py    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 8
Project: FCOS_GluonCV   Author: DetectionTeamUCAS   File: network.py    Apache License 2.0 6 votes vote down vote up
def plot_network(block, shape=(1, 3, 224, 224), save_prefix=None):
    """Plot network to visualize internal structures.

    Parameters
    ----------
    block : mxnet.gluon.HybridBlock
        A hybridizable network to be visualized.
    shape : tuple of int
        Desired input shape, default is (1, 3, 224, 224).
    save_prefix : str or None
        If not `None`, will save rendered pdf to disk with prefix.

    """
    if graphviz is None:
        raise RuntimeError("Cannot import graphviz.")
    if not isinstance(block, gluon.HybridBlock):
        raise ValueError("block must be HybridBlock, given {}".format(type(block)))
    data = mx.sym.var('data')
    sym = block(data)
    a = mx.viz.plot_network(sym, shape={'data':shape},
                            node_attrs={'shape':'rect', 'fixedsize':'false'})
    a.view(tempfile.mktemp('.gv'))
    if isinstance(save_prefix, str):
        a.render(save_prefix) 
Example 9
Project: o2g   Author: hiposfer   File: web.py    MIT License 6 votes vote down vote up
def dl_osm_from_overpass(area, bbox):
    if not area and not bbox:
        raise Exception('At lease area or bbox must be given.')

    overpass_query = build_overpass_query(area, bbox)
    overpass_api_url = "http://overpass-api.de/api/interpreter"

    filepath = tempfile.mktemp(suffix='_overpass.osm')
    resp = urlopen(overpass_api_url, overpass_query.encode('utf-8'))

    if resp.status == 200:
        with open(filepath, 'w') as osm:
            osm.write(resp.read().decode('utf-8'))
        return os.path.split(filepath)[-1], filepath
    else:
        raise urllib.request.HTTPError(
            'Error calling Overpass API. Status: {}, reason: {}'.format(
                resp.status, resp.reason))

    raise Exception("Can't download data form overpass api.") 
Example 10
Project: storjnode   Author: StorjOld   File: encryptedio.py    MIT License 6 votes vote down vote up
def test_roundtrip(self):
        input_path = __file__
        encrypted_path = tempfile.mktemp()
        output_path = tempfile.mktemp()

        # encrypt
        with open(input_path, 'rb') as fi, open(encrypted_path, 'wb') as fo:
            storjnode.encryptedio.symmetric_encrypt(fi, fo, b"test")

        # decrypt
        with open(encrypted_path, 'rb') as fi, open(output_path, 'wb') as fo:
            storjnode.encryptedio.symmetric_decrypt(fi, fo, b"test")

        # check hashes
        with open(input_path, 'rb') as input_file:
            input_hash = hashlib.sha256(input_file.read()).hexdigest()
        with open(output_path, 'rb') as output_file:
            output_hash = hashlib.sha256(output_file.read()).hexdigest()
        self.assertEqual(input_hash, output_hash)

        # TODO add openssl compatibility tests (already tested manually) 
Example 11
Project: storjnode   Author: StorjOld   File: config.py    MIT License 6 votes vote down vote up
def test_save_overwrites(self):
        path = tempfile.mktemp()
        try:

            # create config
            cfg = storjnode.config.create(self.btctxstore)
            created_data = storjnode.config.save(self.btctxstore, path, cfg)

            # update config
            updated_cfg = copy.deepcopy(created_data)
            address = "1A8WqiJDh3tGVeEefbMN5BVDYxx2XSoWgG"
            updated_cfg["payout_address"] = address
            storjnode.config.save(self.btctxstore, path, updated_cfg)

            # confirm overwriten
            loaded_cfg = storjnode.config.read(path)
            self.assertEqual(updated_cfg, loaded_cfg)
        finally:
            os.remove(path) 
Example 12
Project: storjnode   Author: StorjOld   File: config.py    MIT License 6 votes vote down vote up
def test_get_migrates_if_needed(self):
        path = tempfile.mktemp()
        try:
            # save unmigrated config
            with open(path, 'w') as fp:
                fp.write(json.dumps(UNMIGRATED_CONFIG))

            # loaded config is migrated and valid
            loaded = storjnode.config.get(self.btctxstore, path)
            self.assertTrue(storjnode.config.validate(self.btctxstore, loaded))

            # check if it was saved
            saved = storjnode.config.read(path)
            self.assertEqual(loaded, saved)
        finally:
            os.remove(path) 
Example 13
Project: ngo-addons-backport   Author: camptocamp   File: ExportToRML.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def GetAFileName(self):
        sFilePickerArgs = Array(10)
        oFileDialog = createUnoService("com.sun.star.ui.dialogs.FilePicker")
        oFileDialog.initialize(sFilePickerArgs)
        oFileDialog.appendFilter("OpenERP Report File Save To ....","*.rml")

        f_path = "OpenERP-"+ os.path.basename( tempfile.mktemp("","") ) + ".rml"
        initPath = tempfile.gettempdir()
        oUcb = createUnoService("com.sun.star.ucb.SimpleFileAccess")
        if oUcb.exists(initPath):
            oFileDialog.setDisplayDirectory('file://' + ( os.name == 'nt' and '/' or '' ) + initPath )

        oFileDialog.setDefaultName(f_path )

        sPath = oFileDialog.execute() == 1 and oFileDialog.Files[0] or ''
        oFileDialog.dispose()
        sPath = sPath[7:]
        if sPath.startswith('localhost/'):
            slash = int(os.name == 'nt')
            sPath = sPath[9 + slash:]
        return sPath 
Example 14
Project: me-ica   Author: ME-ICA   File: test_node_operations.py    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 15
Project: me-ica   Author: ME-ICA   File: test_flows.py    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 16
Project: flight-lab   Author: google   File: display.py    Apache License 2.0 6 votes vote down vote up
def __init__(self, chrome_path, *args, **kwargs):
    """Creates Display instance.

    Args:
      chrome_path: path to chrome executable.
    """
    super(Display, self).__init__(*args, **kwargs)
    self._chrome_path = chrome_path
    self._temp_path = tempfile.gettempdir()
    self._index_file = tempfile.mktemp(suffix='.html')
    self._chrome_app = app.Application(
        name='Browser',
        bin_path=chrome_path,
        arguments=[
            '--kiosk', self._index_file, '--new-window', '--incognito',
            '--noerrordialogs', '--user-data-dir={0}'.format(self._temp_path)
        ],
        restart_on_crash=True) 
Example 17
Project: py   Author: pytest-dev   File: test_local.py    MIT License 6 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 18
Project: rex   Author: angr   File: cgc_exploit.py    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
Project: rex   Author: angr   File: cgc_exploit_factory.py    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 20
Project: LaserTOF   Author: kyleuckert   File: test_format.py    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 21
Project: jumpserver-python-sdk   Author: jumpserver   File: test_auth.py    GNU General Public License v2.0 5 votes vote down vote up
def test_save_to_f(self):
        tmpf = tempfile.mktemp()
        self.access_key.save_to_f(tmpf)
        print(tmpf)
        with open(tmpf, 'rt') as f:
            val = f.read().strip()
            self.assertEqual(val, self.access_key_val)
        os.unlink(tmpf) 
Example 22
Project: jumpserver-python-sdk   Author: jumpserver   File: test_auth.py    GNU General Public License v2.0 5 votes vote down vote up
def setUp(self):
        self.access_key_val = "123:123"
        self.id = "123"
        self.secret = "123"
        self.access_key = AccessKey("123", "123")
        self.key_env_var = "XXX_ACCESS_KEY"
        self.key_file = tempfile.mktemp()
        config = {
            'ACCESS_KEY_ENV': self.key_env_var,
            'ACCESS_KEY': self.access_key_val,
            'ACCESS_KEY_FILE': self.key_file,
        }
        self.mock_app = MockApp(config)
        self.app_access_key = AppAccessKey(self.mock_app) 
Example 23
Project: pyblish-win   Author: pyblish   File: pydoc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tempfilepager(text, cmd):
    """Page through text by invoking a program on a temporary file."""
    import tempfile
    filename = tempfile.mktemp()
    file = open(filename, 'w')
    file.write(_encode(text))
    file.close()
    try:
        os.system(cmd + ' "' + filename + '"')
    finally:
        os.unlink(filename) 
Example 24
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def commit(self, db):
        from tempfile import mktemp
        filename = mktemp()
        FCICreate(filename, self.files)
        add_data(db, "Media",
                [(1, self.index, None, "#"+self.name, None, None)])
        add_stream(db, self.name, filename)
        os.unlink(filename)
        db.Commit() 
Example 25
Project: pyblish-win   Author: pyblish   File: platform.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self,cmd,mode='r',bufsize=None):

        if mode != 'r':
            raise ValueError,'popen()-emulation only supports read mode'
        import tempfile
        self.tmpfile = tmpfile = tempfile.mktemp()
        os.system(cmd + ' > %s' % tmpfile)
        self.pipe = open(tmpfile,'rb')
        self.bufsize = bufsize
        self.mode = mode 
Example 26
Project: pyblish-win   Author: pyblish   File: doctest.py    GNU Lesser 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
Project: pyblish-win   Author: pyblish   File: test_bytes.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_bytearray_api(self):
        short_sample = b"Hello world\n"
        sample = short_sample + b"\0"*(20 - len(short_sample))
        tfn = tempfile.mktemp()
        try:
            # Prepare
            with open(tfn, "wb") as f:
                f.write(short_sample)
            # Test readinto
            with open(tfn, "rb") as f:
                b = bytearray(20)
                n = f.readinto(b)
            self.assertEqual(n, len(short_sample))
            # Python 2.x
            b_sample = (ord(s) for s in sample)
            self.assertEqual(list(b), list(b_sample))
            # Test writing in binary mode
            with open(tfn, "wb") as f:
                f.write(b)
            with open(tfn, "rb") as f:
                self.assertEqual(f.read(), sample)
            # Text mode is ambiguous; don't test
        finally:
            try:
                os.remove(tfn)
            except os.error:
                pass 
Example 28
Project: pyblish-win   Author: pyblish   File: test_tempfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, dir, pre, suf):
            self.name = tempfile.mktemp(dir=dir, prefix=pre, suffix=suf)
            # Create the file.  This will raise an exception if it's
            # mysteriously appeared in the meanwhile.
            os.close(os.open(self.name, self._bflags, 0600)) 
Example 29
Project: pyblish-win   Author: pyblish   File: test_tempfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def do_create(self, pre="", suf=""):
        try:
            file = self.mktemped(self.dir, pre, suf)
        except:
            self.failOnException("mktemp")

        self.nameCheck(file.name, self.dir, pre, suf)
        return file 
Example 30
Project: pyblish-win   Author: pyblish   File: test_tempfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_basic(self):
        # mktemp can choose usable file names
        self.do_create()
        self.do_create(pre="a")
        self.do_create(suf="b")
        self.do_create(pre="a", suf="b")
        self.do_create(pre="aa", suf=".txt") 
Example 31
Project: pyblish-win   Author: pyblish   File: test_subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def mkstemp():
        """Replacement for mkstemp, calling mktemp."""
        fname = tempfile.mktemp()
        return os.open(fname, os.O_RDWR|os.O_CREAT), fname 
Example 32
Project: pyblish-win   Author: pyblish   File: test_shutil.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_rmtree_errors(self):
        # filename is guaranteed not to exist
        filename = tempfile.mktemp()
        self.assertRaises(OSError, shutil.rmtree, filename) 
Example 33
Project: pyblish-win   Author: pyblish   File: test_shutil.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_move_dir(self):
        # Move a dir to another location on the same filesystem.
        dst_dir = tempfile.mktemp()
        try:
            self._check_move_dir(self.src_dir, dst_dir, dst_dir)
        finally:
            try:
                shutil.rmtree(dst_dir)
            except:
                pass 
Example 34
Project: flasky   Author: RoseOu   File: doctest.py    MIT License 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 35
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: test_recordio.py    Apache License 2.0 5 votes vote down vote up
def test_recordio_pack_label():
    frec = tempfile.mktemp()
    N = 255

    for i in range(1, N):
        for j in range(N):
            content = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(j))
            content = content.encode('utf-8')
            label = np.random.uniform(size=i).astype(np.float32)
            header = (0, label, 0, 0)
            s = mx.recordio.pack(header, content)
            rheader, rcontent = mx.recordio.unpack(s)
            assert (label == rheader.label).all()
            assert content == rcontent 
Example 36
Project: o2g   Author: hiposfer   File: web.py    MIT License 5 votes vote down vote up
def dl_osm_from_url(url):
    filename = tempfile.mktemp(suffix=pathlib.Path(url).name)
    filepath, headers =\
        urllib.request.urlretrieve(url, filename=filename)
    return pathlib.Path(url).name, filepath 
Example 37
Project: o2g   Author: hiposfer   File: cli.py    MIT License 5 votes vote down vote up
def capture_logs():
    logfile = tempfile.mktemp()
    handler = FileHandler(logfile, mode='w')
    logging.getLogger().addHandler(handler)
    try:
        yield logfile
    finally:
        logging.getLogger().removeHandler(handler) 
Example 38
Project: o2g   Author: hiposfer   File: test_validation.py    MIT License 5 votes vote down vote up
def dummy_zipfeed(dummy_gtfs_writer):
    filename = '{}.zip'.format(tempfile.mktemp())
    print('Writing GTFS feed to %s' % filename)
    dummy_gtfs_writer.write_zipped(filename)

    return filename 
Example 39
Project: o2g   Author: hiposfer   File: test_validation.py    MIT License 5 votes vote down vote up
def test_write_zipped(gtfs_writer):
    filename = tempfile.mktemp()
    print('Writing GTFS feed to %s' % filename)
    gtfs_writer.write_zipped(filename)

    assert os.path.exists(filename) 
Example 40
Project: parfive   Author: Cadair   File: test_utils.py    MIT License 5 votes vote down vote up
def test_sha256sum():
    tempfilename = tempfile.mktemp()
    filehash = "559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd"
    with open(tempfilename, 'w') as f:
        f.write('A')
    assert sha256sum(tempfilename) == filehash 
Example 41
Project: storjnode   Author: StorjOld   File: shard.py    MIT License 5 votes vote down vote up
def test_save(self):
        save_path = tempfile.mktemp()
        storjnode.storage.shard.save(self.shard, save_path)
        filecmp.cmp(SHARD_PATH, save_path)
        os.remove(save_path) 
Example 42
Project: storjnode   Author: StorjOld   File: config.py    MIT License 5 votes vote down vote up
def test_roundtrip_unencrypted(self):
        path = tempfile.mktemp()
        try:
            cfg = storjnode.config.create(self.btctxstore)
            saved_data = storjnode.config.save(self.btctxstore, path, cfg)
            loaded_cfg = storjnode.config.read(path)
            self.assertEqual(saved_data, loaded_cfg)
        finally:
            os.remove(path) 
Example 43
Project: storjnode   Author: StorjOld   File: config.py    MIT License 5 votes vote down vote up
def test_get_loads_config(self):
        path = tempfile.mktemp()
        try:
            cfg = storjnode.config.create(self.btctxstore)
            created_cfg = storjnode.config.save(self.btctxstore, path, cfg)
            loaded_cfg = storjnode.config.get(self.btctxstore, path)
            self.assertEqual(created_cfg, loaded_cfg)
        finally:
            os.remove(path) 
Example 44
Project: ngo-addons-backport   Author: camptocamp   File: ExportToRML.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, ctx):
        self.ctx     = ctx
        self.module  = "openerp_report"
        self.version = "0.1"
        LoginTest()
        if not loginstatus and __name__=="package":
            exit(1)

        desktop=getDesktop()
        doc = desktop.getCurrentComponent()
        docinfo=doc.getDocumentInfo()
        global url
        self.sock=RPCSession(url)

        # Read Data from sxw file
        tmpsxw = tempfile.mktemp('.'+"sxw")

        if not doc.hasLocation():
            mytype = Array(makePropertyValue("MediaType","application/vnd.sun.xml.writer"),)
            doc.storeAsURL("file://"+tmpsxw,mytype)
        data = read_data_from_file( get_absolute_file_path( doc.getURL()[7:] ) )
        file_type = doc.getURL()[7:].split(".")[-1]
        if docinfo.getUserFieldValue(2) == "":
            ErrorDialog("Please Save this file on server","Use Send To Server Option in OpenERP Report Menu","Error")
            exit(1)
        filename = self.GetAFileName()
        if not filename:
            exit(1)
        global passwd
        self.password = passwd
        try:

            res = self.sock.execute(database, uid, self.password, 'ir.actions.report.xml', 'sxwtorml',base64.encodestring(data),file_type)
            if res['report_rml_content']:
                write_data_to_file(get_absolute_file_path(filename), res['report_rml_content'])
        except Exception,e:
            import traceback,sys
            info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
            self.logobj.log_write('ExportToRML',LOG_ERROR, info)
            ErrorDialog("Cannot save the file to the hard drive.", "Exception: %s." % e, "Error" ) 
Example 45
Project: openhatch   Author: campbe13   File: test_log.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def test_setup_logger_no_handlers_file(self):
        l = self.get_logger()
        set_handlers(l, [])
        tempfile = mktemp(suffix="unittest", prefix="celery")
        l = self.setup_logger(logfile=tempfile, loglevel=0, root=False)
        self.assertIsInstance(get_handlers(l)[0],
                              logging.FileHandler) 
Example 46
Project: openhatch   Author: campbe13   File: decompression.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _is_tar(self, response):
        archive = StringIO(response.body)
        try:
            tar_file = tarfile.open(name=mktemp(), fileobj=archive)
        except tarfile.ReadError:
            return

        body = tar_file.extractfile(tar_file.members[0]).read()
        respcls = responsetypes.from_args(filename=tar_file.members[0].name, body=body)
        return response.replace(body=body, cls=respcls) 
Example 47
Project: jawfish   Author: war-and-code   File: pydoc.py    MIT License 5 votes vote down vote up
def tempfilepager(text, cmd):
    """Page through text by invoking a program on a temporary file."""
    import tempfile
    filename = tempfile.mktemp()
    file = open(filename, 'w')
    file.write(text)
    file.close()
    try:
        os.system(cmd + ' "' + filename + '"')
    finally:
        os.unlink(filename) 
Example 48
Project: web2mpv_settings   Author: alex8224   File: ytb.py    GNU General Public License v3.0 5 votes vote down vote up
def get_srtname():
    return tempfile.mktemp() 
Example 49
Project: web2mpv_settings   Author: alex8224   File: ytb.py    GNU General Public License v3.0 5 votes vote down vote up
def download_srt(url):
    if has_danmu(url):
        html_body = you_get.common.get_content(url)
        cid = find_cid(html_body)
        if cid:
            srt_data = you_get.common.get_content("http://comment.bilibili.com/%s.xml" % cid)
            srt_filename = tempfile.mktemp()
            with open(srt_filename, "wb") as srtfile:
                srtfile.write(bytes(srt_data, "utf-8"))
            return danmu2ass(srt_filename)    
    else:
        return False 
Example 50
Project: web2mpv_settings   Author: alex8224   File: ytb.py    GNU General Public License v3.0 5 votes vote down vote up
def get_srtname():
    return tempfile.mktemp() 
Example 51
Project: web2mpv_settings   Author: alex8224   File: ytb.py    GNU General Public License v3.0 5 votes vote down vote up
def download_srt(url):
    if has_danmu(url):
        html_body = you_get.common.get_content(url)
        cid = find_cid(html_body)
        if cid:
            srt_data = you_get.common.get_content("http://comment.bilibili.com/%s.xml" % cid)
            srt_filename = tempfile.mktemp()
            with open(srt_filename, "w") as srtfile:
                srtfile.write(srt_data)
            return danmu2ass(srt_filename)    
    else:
        return False 
Example 52
Project: inmanta   Author: inmanta   File: conftest.py    Apache License 2.0 5 votes vote down vote up
def _do_export(self, deploy=False, include_status=False, do_raise=True):
        """
        helper function to allow actual export to be run an a different thread
        i.e. export.run must run off main thread to allow it to start a new ioloop for run_sync
        """
        templfile = mktemp("json", "dump", self.project_dir)

        class Options(object):
            pass

        options = Options()
        options.json = templfile if not deploy else None
        options.depgraph = False
        options.deploy = deploy
        options.ssl = False

        from inmanta.export import Exporter  # noqa: H307

        try:
            (types, scopes) = compiler.do_compile()
        except Exception:
            types, scopes = (None, None)
            if do_raise:
                raise
            else:
                traceback.print_exc()

        # Even if the compile failed we might have collected additional data such as unknowns. So
        # continue the export
        export = Exporter(options)

        return export.run(types, scopes, model_export=False, include_status=include_status) 
Example 53
Project: fabulist   Author: mar10   File: test.py    MIT License 5 votes vote down vote up
def test_save(self):
        self.temp_path = tempfile.mktemp()
        wl = self.fab.list_map["adj"]
        self.fab.load()
        wl.save_as(self.temp_path)
        assert os.path.getsize(self.temp_path) > 1000 
Example 54
Project: JukeBox   Author: gauravsarkar97   File: image_test.py    MIT License 5 votes vote down vote up
def testSavePNG32(self):
        """ see if we can save a png with color values in the proper channels.
        """
        # Create a PNG file with known colors
        reddish_pixel = (215, 0, 0, 255)
        greenish_pixel = (0, 225, 0, 255)
        bluish_pixel = (0, 0, 235, 255)
        greyish_pixel = (115, 125, 135, 145)

        surf = pygame.Surface((1, 4), pygame.SRCALPHA, 32)
        surf.set_at((0, 0), reddish_pixel)
        surf.set_at((0, 1), greenish_pixel)
        surf.set_at((0, 2), bluish_pixel)
        surf.set_at((0, 3), greyish_pixel)

        f_path = tempfile.mktemp(suffix='.png')
        pygame.image.save(surf, f_path)

        # Read the PNG file and verify that pygame saved it correctly
        width, height, pixels, metadata = png.Reader(filename=f_path).asRGBA8()
        pixels_as_tuples = []
        for pixel in pixels:
            pixels_as_tuples.append(tuple(pixel))

        self.assertEquals(pixels_as_tuples[0], reddish_pixel)
        self.assertEquals(pixels_as_tuples[1], greenish_pixel)
        self.assertEquals(pixels_as_tuples[2], bluish_pixel)
        self.assertEquals(pixels_as_tuples[3], greyish_pixel)

        os.remove(f_path) 
Example 55
Project: JukeBox   Author: gauravsarkar97   File: image_test.py    MIT License 5 votes vote down vote up
def testSavePNG24(self):
        """ see if we can save a png with color values in the proper channels.
        """
        # Create a PNG file with known colors
        reddish_pixel = (215, 0, 0)
        greenish_pixel = (0, 225, 0)
        bluish_pixel = (0, 0, 235)
        greyish_pixel = (115, 125, 135)

        surf = pygame.Surface((1, 4), 0, 24)
        surf.set_at((0, 0), reddish_pixel)
        surf.set_at((0, 1), greenish_pixel)
        surf.set_at((0, 2), bluish_pixel)
        surf.set_at((0, 3), greyish_pixel)

        f_path = tempfile.mktemp(suffix='.png')
        pygame.image.save(surf, f_path)

        # Read the PNG file and verify that pygame saved it correctly
        width, height, pixels, metadata = png.Reader(filename=f_path).asRGB8()
        pixels_as_tuples = []
        for pixel in pixels:
            pixels_as_tuples.append(tuple(pixel))

        self.assertEquals(pixels_as_tuples[0], reddish_pixel)
        self.assertEquals(pixels_as_tuples[1], greenish_pixel)
        self.assertEquals(pixels_as_tuples[2], bluish_pixel)
        self.assertEquals(pixels_as_tuples[3], greyish_pixel)

        os.remove(f_path) 
Example 56
Project: recipes-py   Author: luci   File: fileutil.py    Apache License 2.0 5 votes vote down vote up
def _FlattenSingleDirectories(path):
  assert os.path.isabs(path), 'nonabs path: %r' % (path,)
  assert os.path.isdir(path), 'nondir path: %r' % (path,)

  first_single_dir = None
  print('flattening single directories in %r' % (path,))
  for root, dirs, files in os.walk(path):
    # if it's a single dir, we keep walking
    if len(dirs) == 1 and not files:
      if not first_single_dir:
        first_single_dir = os.path.join(path, dirs[0])
      continue

    # otherwise we found some stuff!
    if not first_single_dir:
      # if we didn't find a first_single_dir, we're still in the base directory
      # and don't have anything to do.
      print('contents appears already flattened')
      return 0

    print('found contents at: %r' % (os.path.relpath(root, path),))

    # first move the first_single_dir out of the way, in case there's
    # a file/folder we need to move that has a conflicting name.
    tmpname = tempfile.mktemp(dir=path)
    print('moving root folder out of the way: %r -> %r' % (first_single_dir, tmpname))
    os.rename(first_single_dir, tmpname)

    for name in itertools.chain(dirs, files):
      fullname = os.path.join(root, name).replace(first_single_dir, tmpname)
      to = os.path.join(path, name)
      print('mv %r %r' % (fullname, to))
      os.rename(fullname, to)
    print('moved %d dirs and %d files' % (len(dirs), len(files)))
    print('rm -rf %r' % (tmpname,))
    shutil.rmtree(tmpname)
    return 0 
Example 57
Project: py   Author: pytest-dev   File: test_local.py    MIT License 5 votes vote down vote up
def path1(tmpdir_factory):
    path = tmpdir_factory.mktemp('path')
    common.setuptestfs(path)
    yield path
    assert path.join("samplefile").check() 
Example 58
Project: rex   Author: angr   File: fuzzing_type_2.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_binary(self, enable_randomness=True, timeout=5):
        """
        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)

        pov_tester = CGCPovSimulator()
        result = pov_tester.test_binary_pov(pov_binary_filename, self.binary, enable_randomness=enable_randomness,
                                            timeout=timeout)
        os.remove(pov_binary_filename)
        return result 
Example 59
Project: rex   Author: angr   File: fuzzing_type_1.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_binary(self):
        """
        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)

        pov_tester = CGCPovSimulator()
        return pov_tester.test_binary_pov(pov_binary_filename, self.binary) 
Example 60
Project: DRCOG_Urbansim   Author: apdjustino   File: creating_baseyear_cache_configuration.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self,
            cache_directory_root = mktemp(prefix='opus_tmp'),
            cache_scenario_database = 'opus_core.cache.cache_scenario_database',
            cache_from_database = True,
            baseyear_cache = None,
            existing_cache_to_copy = None,
            years_to_cache = BaseyearCacheConfiguration.ALL_YEARS,
            tables_to_cache = [],
            tables_to_cache_nchunks = {},
            tables_to_copy_to_previous_years = {},
            scenario_database_configuration = None,
            ):
        
        if (baseyear_cache is None) and existing_cache_to_copy:
            baseyear_cache = BaseyearCacheConfiguration(existing_cache_to_copy,
                                                        years_to_cache=years_to_cache)        
        if baseyear_cache is None and not cache_from_database:
            raise TypeError("Parameter 'baseyear_cache' must be specified if "
                "parameter 'cache_from_database' is not True!")
        
        self.scenario_database_configuration = scenario_database_configuration
        self.baseyear_cache = baseyear_cache
        self.cache_directory_root = cache_directory_root
        self.cache_from_database = cache_from_database
        self.cache_scenario_database = cache_scenario_database
        self.tables_to_cache = tables_to_cache
        self.tables_to_cache_nchunks = tables_to_cache_nchunks
        self.tables_to_copy_to_previous_years = tables_to_copy_to_previous_years 
Example 61
Project: DRCOG_Urbansim   Author: apdjustino   File: file_utilities.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.file_name = tempfile.mktemp() 
Example 62
Project: DRCOG_Urbansim   Author: apdjustino   File: coefficients.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def test_make_tex_table(self):
        coef = Coefficients(names=array(["coef1", "coef2"]), values = array([0.5, 0.00001]),
                             standard_errors=array([0.02, 0.0000001]),
                             other_measures={"t_stat":array([2.5, 4.99999])})
        from tempfile import mktemp
        tmp_file_prefix = mktemp()
        try:
            coef.make_tex_table(tmp_file_prefix)
        finally:
            os.remove('%s.tex' % tmp_file_prefix) 
Example 63
Project: honeybee   Author: ladybug-tools   File: radiance_command_getinfo_test.py    GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        """Set up the test case by initiating the class."""
        get_info = Getinfo()
        get_info.input_file = os.path.abspath('tests/assets/sample.hdr')
        get_info.output_file = os.path.abspath(tempfile.mktemp(suffix='.txt'))
        self.getinfo_test1 = get_info
        self.output_file1 = get_info.output_file

    # ending the test 
Example 64
Project: honeybee   Author: ladybug-tools   File: genBSDF.py    GNU General Public License v3.0 5 votes vote down vote up
def prepare_geometry_for_bsdf(self):
        """A method that will translate and rotate the model properly for genBSDF.
        """
        assert self.input_geometry,\
            'The files required for input_geometry have not been specified'

        assert self.normal_orientation._value, \
            'The input required for normal_orientation has not been specified'

        temp_for_getbox = tempfile.mktemp(prefix='getb')

        get_b = Getbbox()
        get_b.rad_files = self.input_geometry
        get_b.output_file = temp_for_getbox
        get_b.header_suppress = True
        get_b.execute()

        with open(temp_for_getbox) as get_box_data:
            get_box_value = get_box_data.read().strip().split()
            xMin, xMax, yMin, yMax, zMin, zMax = map(float, get_box_value)

        os.remove(temp_for_getbox)

        temp_for_xform = tempfile.mktemp(prefix='xform')

        xTr, yTr, zTr = 0 - xMin, 0 - yMin, 0 - zMin
        zTr += -0.001

        rotation_dict = {'+x': '-ry -90', '-x': '-ry 90',
                         '+y': '-rx 90', '-y': '-rx -90',
                         '+z': '', '-z': ''}
        rotation_normal = self.normal_orientation._value.lower()

        rot_tr = rotation_dict[rotation_normal]
        xfr = Xform()
        xfr.rad_file = [os.path.abspath(geo) for geo in self.input_geometry]
        xfr.transforms = "-t %s %s %s %s" % (xTr, yTr, zTr, rot_tr)
        xfr.output_file = temp_for_xform
        xfr.execute()

        return temp_for_xform 
Example 65
Project: analyzer-website   Author: santiagolizardo   File: test_proxies.py    GNU Affero General Public License v3.0 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 66
Project: Flask_Blog   Author: sugarguo   File: doctest.py    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 67
Project: pulsar-cloud   Author: quantmind   File: __init__.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __enter__(self):
        self.filename = tempfile.mktemp()
        with open(self.filename, 'wb') as fout:
            fout.write(os.urandom(self.size))
        return self 
Example 68
Project: LaserTOF   Author: kyleuckert   File: test_multiarray.py    MIT License 5 votes vote down vote up
def setUp(self):
        shape = (2, 4, 3)
        rand = np.random.random
        self.x = rand(shape) + rand(shape).astype(np.complex)*1j
        self.x[0,:, 1] = [np.nan, np.inf, -np.inf, np.nan]
        self.dtype = self.x.dtype
        self.tempdir = tempfile.mkdtemp()
        self.filename = tempfile.mktemp(dir=self.tempdir) 
Example 69
Project: LaserTOF   Author: kyleuckert   File: test_memmap.py    MIT License 5 votes vote down vote up
def test_open_with_filename(self):
        tmpname = mktemp('', 'mmap', dir=self.tempdir)
        fp = memmap(tmpname, dtype=self.dtype, mode='w+',
                       shape=self.shape)
        fp[:] = self.data[:]
        del fp 
Example 70
Project: LaserTOF   Author: kyleuckert   File: test_memmap.py    MIT License 5 votes vote down vote up
def test_filename(self):
        tmpname = mktemp('', 'mmap', dir=self.tempdir)
        fp = memmap(tmpname, dtype=self.dtype, mode='w+',
                       shape=self.shape)
        abspath = os.path.abspath(tmpname)
        fp[:] = self.data[:]
        self.assertEqual(abspath, fp.filename)
        b = fp[:1]
        self.assertEqual(abspath, b.filename)
        del b
        del fp 
Example 71
Project: LaserTOF   Author: kyleuckert   File: test_memmap.py    MIT License 5 votes vote down vote up
def test_path(self):
        tmpname = mktemp('', 'mmap', dir=self.tempdir)
        fp = memmap(Path(tmpname), dtype=self.dtype, mode='w+',
                       shape=self.shape)
        abspath = os.path.realpath(os.path.abspath(tmpname))
        fp[:] = self.data[:]
        self.assertEqual(abspath, str(fp.filename.resolve()))
        b = fp[:1]
        self.assertEqual(abspath, str(b.filename.resolve()))
        del b
        del fp 
Example 72
Project: NiujiaoDebugger   Author: MrSrc   File: pydoc.py    GNU General Public License v3.0 5 votes vote down vote up
def tempfilepager(text, cmd):
    """Page through text by invoking a program on a temporary file."""
    import tempfile
    filename = tempfile.mktemp()
    with open(filename, 'w', errors='backslashreplace') as file:
        file.write(text)
    try:
        os.system(cmd + ' "' + filename + '"')
    finally:
        os.unlink(filename) 
Example 73
Project: NiujiaoDebugger   Author: MrSrc   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def commit(self, db):
        from tempfile import mktemp
        filename = mktemp()
        FCICreate(filename, self.files)
        add_data(db, "Media",
                [(1, self.index, None, "#"+self.name, None, None)])
        add_stream(db, self.name, filename)
        os.unlink(filename)
        db.Commit() 
Example 74
Project: pyblish-win   Author: pyblish   File: connection.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def arbitrary_address(family):
    '''
    Return an arbitrary free address for the given family
    '''
    if family == 'AF_INET':
        return ('localhost', 0)
    elif family == 'AF_UNIX':
        return tempfile.mktemp(prefix='listener-', dir=get_temp_dir())
    elif family == 'AF_PIPE':
        return tempfile.mktemp(prefix=r'\\.\pipe\pyc-%d-%d-' %
                               (os.getpid(), _mmap_counter.next()), dir="")
    else:
        raise ValueError('unrecognized family') 
Example 75
Project: ngo-addons-backport   Author: camptocamp   File: ModifyExistingReport.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def btnOk_clicked(self, oActionEvent):
        try:
            desktop=getDesktop()
            doc = desktop.getCurrentComponent()
            docinfo=doc.getDocumentInfo()

            selectedItemPos = self.win.getListBoxSelectedItemPos( "lstReport" )
            id = self.report_with_id[ selectedItemPos ][0]

            res = self.sock.execute(database, uid, self.password, 'ir.actions.report.xml', 'report_get', id)

            if res['file_type'] in ['sxw','odt'] :
               file_type = res['file_type']
            else :
               file_type = 'sxw'

            fp_name = tempfile.mktemp('.'+file_type)
            fp_name1="r"+fp_name
            fp_path=os.path.join(fp_name1).replace("\\","/")
            fp_win=fp_path[1:]

            filename = ( os.name == 'nt' and fp_win or fp_name )
            if res['report_sxw_content']:
                write_data_to_file( filename, base64.decodestring(res['report_sxw_content']))
            url = "file:///%s" % filename

            arr=Array(makePropertyValue("MediaType","application/vnd.sun.xml.writer"),)
            oDoc2 = desktop.loadComponentFromURL(url, "openerp", 55, arr)
            docinfo2=oDoc2.getDocumentInfo()
            docinfo2.setUserFieldValue(0, self.hostname)
            docinfo2.setUserFieldValue(1,self.password)
            docinfo2.setUserFieldValue(2,id)
            docinfo2.setUserFieldValue(3,self.report_with_id[selectedItemPos][2])

            oParEnum = oDoc2.getTextFields().createEnumeration()
            while oParEnum.hasMoreElements():
                oPar = oParEnum.nextElement()
                if oPar.supportsService("com.sun.star.text.TextField.DropDown"):
                    oPar.SelectedItem = oPar.Items[0]
                    oPar.update()
            if oDoc2.isModified():
                if oDoc2.hasLocation() and not oDoc2.isReadonly():
                    oDoc2.store()

            ErrorDialog("Download is completed.","Your file has been placed here :\n ."+ fp_name,"Download Message !")
            obj=Logger()
            obj.log_write('Modify Existing Report',LOG_INFO, ':successful download report  %s  using database %s' % (self.report_with_id[selectedItemPos][2], database))
        except Exception, e:
            ErrorDialog("The report could not be downloaded.", "Report: %s\nDetails: %s" % ( fp_name, str(e) ),"Download Message !")
            import traceback,sys
            info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
            self.logobj.log_write('ModifyExistingReport', LOG_ERROR, info) 
Example 76
Project: PIL-RCE-Ghostscript-CVE-2018-16509   Author: farisv   File: app.py    MIT License 4 votes vote down vote up
def upload_file():
    if request.method == 'POST':
        file = request.files.get('image', None)

        if not file:
            flash('No image found')
            return redirect(request.url)

        filename = file.filename
        ext = path.splitext(filename)[1]

        if (ext not in ['.jpg', '.jpeg', '.png', '.gif', '.bmp']):
            flash('Invalid extension')
            return redirect(request.url)

        tmp = tempfile.mktemp("test")
        img_path = "{}.{}".format(tmp, ext)

        file.save(img_path)

        img = Image.open(img_path)
        w, h = img.size
        ratio = 256.0 / max(w, h)

        resized_img = img.resize((int(w * ratio), int(h * ratio)))
        resized_img.save(img_path)

        r = make_response()
        r.data = open(img_path, "rb").read()
        r.headers['Content-Disposition'] = 'attachment; filename=resized_{}'.format(filename)

        unlink(img_path)

        return r

    return render_template_string('''
    <!doctype html>
    <title>Image Resizer</title>
    <h1>Upload an Image to Resize</h1>
    {% with messages = get_flashed_messages() %}
    {% if messages %}
        <ul class=flashes>
        {% for message in messages %}
        <li>{{ message }}</li>
        {% endfor %}
        </ul>
    {% endif %}
    {% endwith %}
    <form method=post enctype=multipart/form-data>
      <p><input type=file name=image>
         <input type=submit value=Upload>
    </form>
    ''') 
Example 77
Project: razzy-spinner   Author: rafasashi   File: doctest_driver.py    GNU General Public License v3.0 4 votes vote down vote up
def debug(self, test, pm=False):
        self.test = test

        # Save the old stdout
        self.save_stdout = sys.stdout

        # Convert the source docstring to a script.
        script = self._script_from_examples(test.docstring)

        # Create a debugger.
        debugger = _OutputRedirectingPdb(sys.stdout)

        # Patch pdb.set_trace to restore sys.stdout during interactive
        # debugging (so it's not still redirected to self._fakeout).
        save_set_trace = pdb.set_trace
        pdb.set_trace = debugger.set_trace

        # Write the script to a temporary file.  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(script)
        f.close()

        # Set up the globals
        test.globs['CHECK_OUTPUT'] = self._check_output
        test.globs['CHECK_EXCEPTION'] = self._check_exception
        test.globs['__print__'] = self._print_if_not_none
        test.globs['__set_trace__'] = debugger.set_trace
        test.globs['__examples__'] = self.test.examples
        try:
            if pm is False:
                debugger.run("execfile(%r)" % srcfilename,
                             test.globs, test.globs)
            else:
                try:
                    sys.stdout = _SpoofOut()
                    try:
                        execfile(srcfilename, test.globs)
                    except bdb.BdbQuit:
                        return
                    except:
                        sys.stdout = self.save_stdout
                        exc_info = sys.exc_info()
                        exc_msg = traceback.format_exception_only(
                            exc_info[0], exc_info[1])[-1]
                        self.save_stdout.write(self.runner.DIVIDER+'\n')
                        self.save_stdout.write('Unexpected exception:\n' +
                                               _indent(exc_msg))
                        raise
                        #self.post_mortem(debugger, exc_info[2])
                finally:
                    sys.stdout = self.save_stdout
        finally:
            sys.set_trace = save_set_trace
            os.remove(srcfilename) 
Example 78
Project: JukeBox   Author: gauravsarkar97   File: image_test.py    MIT License 4 votes vote down vote up
def testSaveJPG(self):
        """ JPG equivalent to issue #211 - color channel swapping

        Make sure the SDL surface color masks represent the rgb memory format
        required by the JPG library. The masks are machine endian dependent
        """

        from pygame import Color, Rect
        
        # The source image is a 2 by 2 square of four colors. Since JPEG is
        # lossy, there can be color bleed. Make each color square 16 by 16,
        # to avoid the significantly color value distorts found at color
        # boundaries due to the compression value set by Pygame.
        square_len = 16
        sz = 2 * square_len, 2 * square_len

        #  +---------------------------------+
        #  | red            | green          |
        #  |----------------+----------------|
        #  | blue           | (255, 128, 64) |
        #  +---------------------------------+
        #
        #  as (rect, color) pairs.
        def as_rect(square_x, square_y):
            return Rect(square_x * square_len, square_y * square_len,
                        square_len, square_len)
        squares = [(as_rect(0, 0), Color("red")),
                   (as_rect(1, 0), Color("green")),
                   (as_rect(0, 1), Color("blue")),
                   (as_rect(1, 1), Color(255, 128, 64))]

        # A surface format which is not directly usable with libjpeg.
        surf = pygame.Surface(sz, 0, 32)
        for rect, color in squares:
            surf.fill(color, rect)

        # Assume pygame.image.Load works correctly as it is handled by the
        # third party SDL_image library.
        f_path = tempfile.mktemp(suffix='.jpg')
        pygame.image.save(surf, f_path)
        jpg_surf = pygame.image.load(f_path)

        # Allow for small differences in the restored colors.
        def approx(c):
            mask = 0xFC
            return pygame.Color(c.r & mask, c.g & mask, c.b & mask)
        offset = square_len // 2
        for rect, color in squares:
            posn = rect.move((offset, offset)).topleft
            self.assertEqual(approx(jpg_surf.get_at(posn)), approx(color)) 
Example 79
Project: pyplis   Author: jgliss   File: inout.py    GNU General Public License v3.0 4 votes vote down vote up
def download_test_data(save_path=None):
    """Download pyplis test data.

    :param save_path: location where path is supposed to be stored

    Code for progress bar was "stolen" `here <http://stackoverflow.com/
    questions/11143767/how-to-make-a-download-with>`_
    (last access date: 11/01/2017)
    -progress-bar-in-python

    """
    from pyplis import URL_TESTDATA
    url = URL_TESTDATA

    dirs = data_search_dirs()
    where = dirs[0]
    fp = join(where, "_paths.txt")
    if not exists(fp):
        where = dirs[1]
        fp = join(where, "_paths.txt")
    if save_path is None or not exists(save_path):
        save_path = where
        logger.info("Save path unspecified")
    else:
        with open(fp, "a") as f:
            f.write("\n" + save_path + "\n")
            logger.info("Adding new path for test data location in "
                  "file _paths.txt: %s" % save_path)
            f.close()

    print_log.info("installing test data at %s" % save_path)

    filename = mktemp('.zip')

    if PGBAR_AVAILABLE:
        widgets = ['Downloading pyplis test data: ', Percentage(), ' ',
                   Bar(marker=RotatingMarker()), ' ',
                   ETA(), ' ', FileTransferSpeed()]

        pbar = ProgressBar(widgets=widgets)

        def dl_progress(count, block_size, total_size):
            if pbar.maxval is None:
                pbar.maxval = total_size
                pbar.start()
            pbar.update(min(count * block_size, total_size))

        urlretrieve(url, filename, reporthook=dl_progress)
        pbar.finish()
    else:
        print_log.info("Downloading Pyplis testdata (this can take a while, install"
              "Progressbar package if you want to receive download info")
        urlretrieve(url, filename)
    thefile = ZipFile(filename)
    print_log.info("Extracting data at: %s (this may take a while)" % save_path)
    thefile.extractall(save_path)
    thefile.close()
    remove(filename)
    print_log.info("Download successfully finished, deleted temporary data file"
          "at: %s" % filename) 
Example 80
Project: NiujiaoDebugger   Author: MrSrc   File: windows_utils.py    GNU General Public License v3.0 4 votes vote down vote up
def pipe(*, duplex=False, overlapped=(True, True), bufsize=BUFSIZE):
    """Like os.pipe() but with overlapped support and using handles not fds."""
    address = tempfile.mktemp(
        prefix=r'\\.\pipe\python-pipe-{:d}-{:d}-'.format(
            os.getpid(), next(_mmap_counter)))

    if duplex:
        openmode = _winapi.PIPE_ACCESS_DUPLEX
        access = _winapi.GENERIC_READ | _winapi.GENERIC_WRITE
        obsize, ibsize = bufsize, bufsize
    else:
        openmode = _winapi.PIPE_ACCESS_INBOUND
        access = _winapi.GENERIC_WRITE
        obsize, ibsize = 0, bufsize

    openmode |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE

    if overlapped[0]:
        openmode |= _winapi.FILE_FLAG_OVERLAPPED

    if overlapped[1]:
        flags_and_attribs = _winapi.FILE_FLAG_OVERLAPPED
    else:
        flags_and_attribs = 0

    h1 = h2 = None
    try:
        h1 = _winapi.CreateNamedPipe(
            address, openmode, _winapi.PIPE_WAIT,
            1, obsize, ibsize, _winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL)

        h2 = _winapi.CreateFile(
            address, access, 0, _winapi.NULL, _winapi.OPEN_EXISTING,
            flags_and_attribs, _winapi.NULL)

        ov = _winapi.ConnectNamedPipe(h1, overlapped=True)
        ov.GetOverlappedResult(True)
        return h1, h2
    except:
        if h1 is not None:
            _winapi.CloseHandle(h1)
        if h2 is not None:
            _winapi.CloseHandle(h2)
        raise


# Wrapper for a pipe handle