Python tempfile.TemporaryFile() Examples

The following are code examples for showing how to use tempfile.TemporaryFile(). 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_zipfile.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_write_pyfile(self):
        with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
            fn = __file__
            if fn.endswith('.pyc') or fn.endswith('.pyo'):
                fn = fn[:-1]

            zipfp.writepy(fn)

            bn = os.path.basename(fn)
            self.assertNotIn(bn, zipfp.namelist())
            self.assertTrue(bn + 'o' in zipfp.namelist() or
                            bn + 'c' in zipfp.namelist())

        with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
            fn = __file__
            if fn.endswith(('.pyc', '.pyo')):
                fn = fn[:-1]

            zipfp.writepy(fn, "testpackage")

            bn = "%s/%s" % ("testpackage", os.path.basename(fn))
            self.assertNotIn(bn, zipfp.namelist())
            self.assertTrue(bn + 'o' in zipfp.namelist() or
                            bn + 'c' in zipfp.namelist()) 
Example 2
Project: pyblish-win   Author: pyblish   File: test_tempfile.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_has_no_name(self):
        # TemporaryFile creates files with no names (on this system)
        dir = tempfile.mkdtemp()
        f = tempfile.TemporaryFile(dir=dir)
        f.write('blat')

        # Sneaky: because this file has no name, it should not prevent
        # us from removing the directory it was created in.
        try:
            os.rmdir(dir)
        except:
            ei = sys.exc_info()
            # cleanup
            f.close()
            os.rmdir(dir)
            self.failOnException("rmdir", ei) 
Example 3
Project: docker-testnet   Author: l-n-s   File: testnet.py    MIT License 6 votes vote down vote up
def make_seed(self, cid):
        """creates a zip reseed file"""
        ri_path = "/home/i2pd/data/router.info"

        with tempfile.TemporaryFile() as fp:
            while True:
                try:
                    arc_data = self.NODES[cid].container.get_archive(ri_path)[0].read()
                    break
                except:
                    time.sleep(0.1)

            fp.write(arc_data)
            fp.seek(0)
            ri_file = tarfile.open(fileobj=fp, mode='r')\
                    .extractfile("router.info").read()
            tf = tempfile.mkstemp()[1]
            with open(tf, 'wb') as f: f.write(ri_file)
            zf = zipfile.ZipFile(self.SEED_FILE, "w")
            zf.write(tf, "ri.dat")
            zf.close()
            os.remove(tf) 
Example 4
Project: google_streetview   Author: rrwen   File: test_api_results.py    MIT License 6 votes vote down vote up
def setUp(self):
    file_path = resource_filename(Requirement.parse('google_streetview'), 'google_streetview/config.json')
    with open(file_path, 'r') as in_file:
      defaults = json.load(in_file)
    params = [{
      'size': '600x300', # max 640x640 pixels
      'location': '46.414382,10.013988',
      'heading': '151.78',
      'pitch': '-0.76',
      'key': defaults['key']
    }]
    self.results = google_streetview.api.results(params)
    tempfile = TemporaryFile()
    self.tempfile = str(tempfile.name)
    tempfile.close()
    self.tempdir = str(TemporaryDirectory().name) 
Example 5
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: test_test_utils.py    Apache License 2.0 6 votes vote down vote up
def test_ipv6_supported(self):
        self.assertIn(test_utils.is_ipv6_supported(), (False, True))

        def fake_open(path):
            raise IOError

        def fake_socket_fail(x, y):
            e = socket.error()
            e.errno = errno.EAFNOSUPPORT
            raise e

        def fake_socket_ok(x, y):
            return tempfile.TemporaryFile()

        with fixtures.MonkeyPatch('socket.socket', fake_socket_fail):
            self.assertFalse(test_utils.is_ipv6_supported())

        with fixtures.MonkeyPatch('socket.socket', fake_socket_ok):
            with fixtures.MonkeyPatch('sys.platform', 'windows'):
                self.assertTrue(test_utils.is_ipv6_supported())

            with fixtures.MonkeyPatch('sys.platform', 'linux2'):
                with fixtures.MonkeyPatch('six.moves.builtins.open',
                                          fake_open):
                    self.assertFalse(test_utils.is_ipv6_supported()) 
Example 6
Project: Paradrop   Author: ParadropLabs   File: device.py    Apache License 2.0 6 votes vote down vote up
def create(ctx):
    """
    Install a chute from the working directory.
    """
    url = "{}/chutes/".format(ctx.obj['base_url'])
    headers = {'Content-Type': 'application/x-tar'}

    if not os.path.exists("paradrop.yaml"):
        raise Exception("No paradrop.yaml file found in working directory.")

    with tempfile.TemporaryFile() as temp:
        tar = tarfile.open(fileobj=temp, mode="w")
        for dirName, subdirList, fileList in os.walk('.'):
            for fname in fileList:
                path = os.path.join(dirName, fname)
                arcname = os.path.normpath(path)
                tar.add(path, arcname=arcname)
        tar.close()

        temp.seek(0)
        res = router_request("POST", url, headers=headers, data=temp)
        data = res.json()
        ctx.invoke(watch, change_id=data['change_id']) 
Example 7
Project: Paradrop   Author: ParadropLabs   File: device.py    Apache License 2.0 6 votes vote down vote up
def update(ctx):
    """
    Update the chute from the working directory.
    """
    url = ctx.obj['chute_url']
    headers = {'Content-Type': 'application/x-tar'}

    if not os.path.exists("paradrop.yaml"):
        raise Exception("No paradrop.yaml file found in working directory.")

    with tempfile.TemporaryFile() as temp:
        tar = tarfile.open(fileobj=temp, mode="w")
        for dirName, subdirList, fileList in os.walk('.'):
            for fname in fileList:
                path = os.path.join(dirName, fname)
                arcname = os.path.normpath(path)
                tar.add(path, arcname=arcname)
        tar.close()

        temp.seek(0)
        res = router_request("PUT", url, headers=headers, data=temp)
        data = res.json()
        ctx.invoke(watch, change_id=data['change_id']) 
Example 8
Project: ngo-addons-backport   Author: camptocamp   File: base_import_language.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def import_lang(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        this = self.browse(cr, uid, ids[0])
        if this.overwrite:
            context.update(overwrite=True)
        fileobj = TemporaryFile('w+')
        try:
            fileobj.write(base64.decodestring(this.data))
    
            # now we determine the file format
            fileobj.seek(0)
            first_line = fileobj.readline().strip().replace('"', '').replace(' ', '')
            fileformat = first_line.endswith("type,name,res_id,src,value") and 'csv' or 'po'
            fileobj.seek(0)
    
            tools.trans_load_data(cr, fileobj, fileformat, this.code, lang_name=this.name, context=context)
        finally:
            fileobj.close()
        return True


# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: 
Example 9
Project: Notmail_Bot   Author: ManuelLR   File: loadConfig.py    GNU General Public License v3.0 6 votes vote down vote up
def is_path_sibling_creatable(pathname: str) -> bool:
    '''
    `True` if the current user has sufficient permissions to create **siblings**
    (i.e., arbitrary files in the parent directory) of the passed pathname;
    `False` otherwise.
    '''
    # Parent directory of the passed path. If empty, we substitute the current
    # working directory (CWD) instead.
    dirname = os.path.dirname(pathname) or os.getcwd()

    try:
        # For safety, explicitly close and hence delete this temporary file
        # immediately after creating it in the passed path's parent directory.
        with tempfile.TemporaryFile(dir=dirname): pass
        return True
    # While the exact type of exception raised by the above function depends on
    # the current version of the Python interpreter, all such types subclass the
    # following exception superclass.
    except EnvironmentError:
        return False 
Example 10
Project: py   Author: pytest-dev   File: capture.py    MIT License 6 votes vote down vote up
def __init__(self, targetfd, tmpfile=None, now=True, patchsys=False):
        """ save targetfd descriptor, and open a new
            temporary file there.  If no tmpfile is
            specified a tempfile.Tempfile() will be opened
            in text mode.
        """
        self.targetfd = targetfd
        if tmpfile is None and targetfd != 0:
            f = tempfile.TemporaryFile('wb+')
            tmpfile = dupfile(f, encoding="UTF-8")
            f.close()
        self.tmpfile = tmpfile
        self._savefd = os.dup(self.targetfd)
        if patchsys:
            self._oldsys = getattr(sys, patchsysdict[targetfd])
        if now:
            self.start() 
Example 11
Project: fs_image   Author: facebookincubator   File: test_subvol_utils.py    MIT License 5 votes vote down vote up
def test_mark_readonly_and_get_sendstream(self, temp_subvols):
        sv = temp_subvols.create('subvol')
        sv.run_as_root(['touch', sv.path('abracadabra')])
        sendstream = sv.mark_readonly_and_get_sendstream()
        self.assertIn(b'abracadabra', sendstream)
        with tempfile.TemporaryFile() as outfile:
            with sv.mark_readonly_and_write_sendstream_to_file(outfile):
                pass
            outfile.seek(0)
            self.assertEqual(sendstream, outfile.read()) 
Example 12
Project: fs_image   Author: facebookincubator   File: test_nspawn_in_subvol.py    MIT License 5 votes vote down vote up
def test_forward_fd(self):
        with tempfile.TemporaryFile() as tf:
            tf.write(b'hello')
            tf.seek(0)
            ret = self._nspawn_in('host', [
                '--forward-fd', str(tf.fileno()), '--', 'sh', '-c',
                'cat <&3 && echo goodbye >&3',
            ], stdout=subprocess.PIPE)
            self.assertEqual(b'hello' + self.maybe_extra_ending, ret.stdout)
            tf.seek(0)
            self.assertEqual(b'hellogoodbye\n', tf.read()) 
Example 13
Project: fs_image   Author: facebookincubator   File: test_nspawn_in_subvol.py    MIT License 5 votes vote down vote up
def test_boot_forward_fd(self):
        with tempfile.TemporaryFile() as tf:
            tf.write(b'hello')
            tf.seek(0)
            ret = self._nspawn_in('bootable-systemd-os', [
                '--boot',
                '--forward-fd', str(tf.fileno()),
                '--',
                '/usr/bin/sh',
                '-c',
                '/usr/bin/cat <&3 && /usr/bin/echo goodbye >&3',
            ], stdout=subprocess.PIPE, check=True)
            self.assertEqual(b'hello', ret.stdout)
            tf.seek(0)
            self.assertEqual(b'hellogoodbye\n', tf.read()) 
Example 14
Project: pyblish-win   Author: pyblish   File: cgi.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def make_file(self, binary=None):
        """Overridable: return a readable & writable file.

        The file will be used as follows:
        - data is written to it
        - seek(0)
        - data is read from it

        The 'binary' argument is unused -- the file is always opened
        in binary mode.

        This version opens a temporary file for reading and writing,
        and immediately deletes (unlinks) it.  The trick (on Unix!) is
        that the file can still be used, but it can't be opened by
        another process, and it will automatically be deleted when it
        is closed or when the current process terminates.

        If you want a more permanent file, you derive a class which
        overrides this method.  If you want a visible temporary file
        that is nevertheless automatically deleted when the script
        terminates, try defining a __del__ method in a derived class
        which unlinks the temporary files you have created.

        """
        import tempfile
        return tempfile.TemporaryFile("w+b")



# Backwards Compatibility Classes
# =============================== 
Example 15
Project: pyblish-win   Author: pyblish   File: test_threadedtempfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def run(self):
        self.errors = StringIO.StringIO()
        startEvent.wait()
        for i in range(FILES_PER_THREAD):
            try:
                f = tempfile.TemporaryFile("w+b")
                f.close()
            except:
                self.error_count += 1
                print_exc(file=self.errors)
            else:
                self.ok_count += 1 
Example 16
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_files(test):
    yield TESTFN2
    with TemporaryFile() as f:
        yield f
        test.assertFalse(f.closed)
    with io.BytesIO() as f:
        yield f
        test.assertFalse(f.closed) 
Example 17
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_stored(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_test(f, zipfile.ZIP_STORED) 
Example 18
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_open_stored(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_open_test(f, zipfile.ZIP_STORED) 
Example 19
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_readline_read_stored(self):
        # Issue #7610: calls to readline() interleaved with calls to read().
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_readline_read_test(f, zipfile.ZIP_STORED) 
Example 20
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_readline_stored(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_readline_test(f, zipfile.ZIP_STORED) 
Example 21
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_readlines_stored(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_readlines_test(f, zipfile.ZIP_STORED) 
Example 22
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_iterlines_stored(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_iterlines_test(f, zipfile.ZIP_STORED) 
Example 23
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_deflated(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_test(f, zipfile.ZIP_DEFLATED) 
Example 24
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_random_open_deflated(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_random_open_test(f, zipfile.ZIP_DEFLATED) 
Example 25
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_readline_read_deflated(self):
        # Issue #7610: calls to readline() interleaved with calls to read().
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_readline_read_test(f, zipfile.ZIP_DEFLATED) 
Example 26
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_readline_deflated(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_readline_test(f, zipfile.ZIP_DEFLATED) 
Example 27
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_readlines_deflated(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_readlines_test(f, zipfile.ZIP_DEFLATED) 
Example 28
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_iterlines_deflated(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_iterlines_test(f, zipfile.ZIP_DEFLATED) 
Example 29
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_large_file_exception(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.large_file_exception_test(f, zipfile.ZIP_STORED)
            self.large_file_exception_test2(f, zipfile.ZIP_STORED) 
Example 30
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_stored(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_test(f, zipfile.ZIP_STORED) 
Example 31
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_deflated(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_test(f, zipfile.ZIP_DEFLATED) 
Example 32
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_write_python_package(self):
        import email
        packagedir = os.path.dirname(email.__file__)

        with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
            zipfp.writepy(packagedir)

            # Check for a couple of modules at different levels of the
            # hierarchy
            names = zipfp.namelist()
            self.assertTrue('email/__init__.pyo' in names or
                            'email/__init__.pyc' in names)
            self.assertTrue('email/mime/text.pyo' in names or
                            'email/mime/text.pyc' in names) 
Example 33
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_write_non_pyfile(self):
        with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
            with open(TESTFN, 'w') as fid:
                fid.write('most definitely not a python file')
            self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
            os.remove(TESTFN) 
Example 34
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_stored(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_test(f, zipfile.ZIP_STORED) 
Example 35
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_deflated(self):
        for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
            self.zip_test(f, zipfile.ZIP_DEFLATED) 
Example 36
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_open_stored(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.zip_open_test(f, zipfile.ZIP_STORED) 
Example 37
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_open_deflated(self):
        for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
            self.zip_open_test(f, zipfile.ZIP_DEFLATED) 
Example 38
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_random_open_deflated(self):
        for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
            self.zip_random_open_test(f, zipfile.ZIP_DEFLATED) 
Example 39
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_read_stored(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.read_test(f, zipfile.ZIP_STORED) 
Example 40
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_readline_read_stored(self):
        # Issue #7610: calls to readline() interleaved with calls to read().
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.readline_read_test(f, zipfile.ZIP_STORED) 
Example 41
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_readline_stored(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.readline_test(f, zipfile.ZIP_STORED) 
Example 42
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_readlines_stored(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.readlines_test(f, zipfile.ZIP_STORED) 
Example 43
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_read_deflated(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.read_test(f, zipfile.ZIP_DEFLATED) 
Example 44
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_readline_read_deflated(self):
        # Issue #7610: calls to readline() interleaved with calls to read().
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.readline_read_test(f, zipfile.ZIP_DEFLATED) 
Example 45
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_readline_deflated(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.readline_test(f, zipfile.ZIP_DEFLATED) 
Example 46
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_readlines_deflated(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.readlines_test(f, zipfile.ZIP_DEFLATED) 
Example 47
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_iterlines_deflated(self):
        for f in (TESTFN2, TemporaryFile(), StringIO()):
            self.iterlines_test(f, zipfile.ZIP_DEFLATED) 
Example 48
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):
        # TemporaryFile can create files
        # No point in testing the name params - the file has no name.
        try:
            tempfile.TemporaryFile()
        except:
            self.failOnException("TemporaryFile") 
Example 49
Project: pyblish-win   Author: pyblish   File: test_tempfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_multiple_close(self):
        # A TemporaryFile can be closed many times without error
        f = tempfile.TemporaryFile()
        f.write('abc\n')
        f.close()
        try:
            f.close()
            f.close()
        except:
            self.failOnException("close")

    # How to test the mode and bufsize parameters? 
Example 50
Project: pyblish-win   Author: pyblish   File: test_subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_stdin_filedes(self):
        # stdin is set to open file descriptor
        tf = tempfile.TemporaryFile()
        d = tf.fileno()
        os.write(d, "pear")
        os.lseek(d, 0, 0)
        p = subprocess.Popen([sys.executable, "-c",
                         'import sys; sys.exit(sys.stdin.read() == "pear")'],
                         stdin=d)
        p.wait()
        self.assertEqual(p.returncode, 1) 
Example 51
Project: pyblish-win   Author: pyblish   File: test_subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_stdin_fileobj(self):
        # stdin is set to open file object
        tf = tempfile.TemporaryFile()
        tf.write("pear")
        tf.seek(0)
        p = subprocess.Popen([sys.executable, "-c",
                         'import sys; sys.exit(sys.stdin.read() == "pear")'],
                         stdin=tf)
        p.wait()
        self.assertEqual(p.returncode, 1) 
Example 52
Project: pyblish-win   Author: pyblish   File: test_subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_stdout_fileobj(self):
        # stdout is set to open file object
        tf = tempfile.TemporaryFile()
        p = subprocess.Popen([sys.executable, "-c",
                          'import sys; sys.stdout.write("orange")'],
                         stdout=tf)
        p.wait()
        tf.seek(0)
        self.assertEqual(tf.read(), "orange") 
Example 53
Project: pyblish-win   Author: pyblish   File: test_subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_stderr_filedes(self):
        # stderr is set to open file descriptor
        tf = tempfile.TemporaryFile()
        d = tf.fileno()
        p = subprocess.Popen([sys.executable, "-c",
                          'import sys; sys.stderr.write("strawberry")'],
                         stderr=d)
        p.wait()
        os.lseek(d, 0, 0)
        self.assertStderrEqual(os.read(d, 1024), "strawberry") 
Example 54
Project: pyblish-win   Author: pyblish   File: test_subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_stderr_fileobj(self):
        # stderr is set to open file object
        tf = tempfile.TemporaryFile()
        p = subprocess.Popen([sys.executable, "-c",
                          'import sys; sys.stderr.write("strawberry")'],
                         stderr=tf)
        p.wait()
        tf.seek(0)
        self.assertStderrEqual(tf.read(), "strawberry") 
Example 55
Project: pyblish-win   Author: pyblish   File: test_subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_stdout_stderr_file(self):
        # capture stdout and stderr to the same open file
        tf = tempfile.TemporaryFile()
        p = subprocess.Popen([sys.executable, "-c",
                          'import sys;'
                          'sys.stdout.write("apple");'
                          'sys.stdout.flush();'
                          'sys.stderr.write("orange")'],
                         stdout=tf,
                         stderr=tf)
        p.wait()
        tf.seek(0)
        self.assertStderrEqual(tf.read(), "appleorange") 
Example 56
Project: pyblish-win   Author: pyblish   File: test_mailbox.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_add_file(self):
        with tempfile.TemporaryFile('w+') as f:
            f.write(_sample_message)
            f.seek(0)
            key = self._box.add(f)
        self.assertEqual(self._box.get_string(key).split('\n'),
            _sample_message.split('\n')) 
Example 57
Project: pyblish-win   Author: pyblish   File: test_zipfile64.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testStored(self):
        # Try the temp file first.  If we do TESTFN2 first, then it hogs
        # gigabytes of disk space for the duration of the test.
        for f in TemporaryFile(), TESTFN2:
            self.zipTest(f, zipfile.ZIP_STORED) 
Example 58
Project: pyblish-win   Author: pyblish   File: test_zipfile64.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testDeflated(self):
            # Try the temp file first.  If we do TESTFN2 first, then it hogs
            # gigabytes of disk space for the duration of the test.
            for f in TemporaryFile(), TESTFN2:
                self.zipTest(f, zipfile.ZIP_DEFLATED) 
Example 59
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: formparser.py    Apache License 2.0 5 votes vote down vote up
def default_stream_factory(total_content_length, filename, content_type,
                           content_length=None):
    """The stream factory that is used per default."""
    if total_content_length > 1024 * 500:
        return TemporaryFile('wb+')
    return BytesIO() 
Example 60
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: formparser.py    Apache License 2.0 5 votes vote down vote up
def default_stream_factory(total_content_length, filename, content_type,
                           content_length=None):
    """The stream factory that is used per default."""
    if total_content_length > 1024 * 500:
        return TemporaryFile('wb+')
    return BytesIO() 
Example 61
Project: docker-ipsec   Author: cbrichford   File: common.py    Apache License 2.0 5 votes vote down vote up
def ipsec(*args) -> IPSecResult:
    cmd_line = ['ipsec']
    cmd_line.extend(args)
        
    with tempfile.TemporaryFile() as output_file:
        status_code = subprocess.call(cmd_line, stdin=subprocess.DEVNULL, stdout=output_file, stderr=output_file)
        output_file.seek(0)
        output = output_file.read().decode("utf-8", "strict")
        return IPSecResult(status=status_code, output=output) 
Example 62
Project: google_streetview   Author: rrwen   File: test_cli.py    MIT License 5 votes vote down vote up
def setUp(self):
    tempfile = TemporaryFile()
    self.tempfile = str(tempfile.name)
    tempfile.close()
    self.tempdir = str(TemporaryDirectory().name) 
Example 63
Project: flasky   Author: RoseOu   File: formparser.py    MIT License 5 votes vote down vote up
def default_stream_factory(total_content_length, filename, content_type,
                           content_length=None):
    """The stream factory that is used per default."""
    if total_content_length > 1024 * 500:
        return TemporaryFile('wb+')
    return BytesIO() 
Example 64
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: test_docker_cache.py    Apache License 2.0 5 votes vote down vote up
def __enter__(self):
        self.buf_output = tempfile.TemporaryFile()

        def trampoline(*popenargs, **kwargs):
            self.call(*popenargs, **kwargs)

        self.old_method = subprocess.call
        subprocess.call = trampoline
        return self 
Example 65
Project: ckanext-geonode   Author: geosolutions-it   File: utils.py    GNU General Public License v2.0 5 votes vote down vote up
def load_wfs_getfeatures(gsbaseurl, typename, outputfile=None, version=WFS_VERSION_200, output_format=WFS_FORMAT_CSV):

    url = gsbaseurl + "/wfs?service=WFS&typename=" \
        + typename + "&outputFormat=" \
        + output_format + "&version=" \
        + version + "&request=GetFeature"

    log.debug('Retrieve WFS GetFeature from %s into %s', url, outputfile)
    log.debug('Retrieve GetFeature for layer: %r', typename)
    log.debug('GetFeature output format: %r', output_format)
    log.debug('GetFeature version: %r', version)

    # TODO: loop to retrieve all the features
    # TODO: stream the output to the file

    http_request = urllib2.Request(url)
    http_response = urllib2.urlopen(http_request)

    content = http_response.read()

    if not outputfile:
        outputfile = tempfile.TemporaryFile()

    outputfile.write(content)
    outputfile.seek(0)

    return outputfile 
Example 66
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: test_utils.py    Apache License 2.0 5 votes vote down vote up
def test_seek_too_far_real_file(self):
        # StringIO doesn't raise IOError if you see past the start of the file.
        with tempfile.TemporaryFile() as flo:
            content = b'1234567890'
            flo.write(content)
            self.assertEqual((content, 0), utils.last_bytes(flo, 1000)) 
Example 67
Project: AshsSDK   Author: thehappydinoa   File: push.py    MIT License 5 votes vote down vote up
def _compress(self, source, ignore_hidden_files=False):
        source_path = os.path.abspath(source)
        appspec_path = os.path.sep.join([source_path, 'appspec.yml'])
        with tempfile.TemporaryFile('w+b') as tf:
            zf = zipfile.ZipFile(tf, 'w', allowZip64=True)
            # Using 'try'/'finally' instead of 'with' statement since ZipFile
            # does not have support context manager in Python 2.6.
            try:
                contains_appspec = False
                for root, dirs, files in os.walk(source, topdown=True):
                    if ignore_hidden_files:
                        files = [fn for fn in files if not fn.startswith('.')]
                        dirs[:] = [dn for dn in dirs if not dn.startswith('.')]
                    for fn in files:
                        filename = os.path.join(root, fn)
                        filename = os.path.abspath(filename)
                        arcname = filename[len(source_path) + 1:]
                        if filename == appspec_path:
                            contains_appspec = True
                        zf.write(filename, arcname, ZIP_COMPRESSION_MODE)
                if not contains_appspec:
                    raise RuntimeError(
                        '{0} was not found'.format(appspec_path)
                    )
            finally:
                zf.close()
            yield tf 
Example 68
Project: Paradrop   Author: ParadropLabs   File: node.py    Apache License 2.0 5 votes vote down vote up
def install_chute(ctx, directory):
    """
    Install a chute from the working directory.

    Install the files in the current directory as a chute on the node.
    The directory must contain a paradrop.yaml file.  The entire directory
    will be copied to the node for installation.
    """
    os.chdir(directory)

    if not os.path.exists("paradrop.yaml"):
        raise Exception("No paradrop.yaml file found in chute directory.")

    client = ctx.obj['client']
    with tempfile.TemporaryFile() as temp:
        tar = tarfile.open(fileobj=temp, mode="w")
        for dirName, subdirList, fileList in os.walk("."):
            for fname in fileList:
                path = os.path.join(dirName, fname)
                arcname = os.path.normpath(path)
                tar.add(path, arcname=arcname)
        tar.close()

        temp.seek(0)
        result = client.install_tar(temp)
        ctx.invoke(watch_change_logs, change_id=result['change_id']) 
Example 69
Project: Paradrop   Author: ParadropLabs   File: node.py    Apache License 2.0 5 votes vote down vote up
def update_chute(ctx, directory):
    """
    Install a new version of the chute from the working directory.

    Install the files in the current directory as a chute on the node.
    The directory must contain a paradrop.yaml file.  The entire directory
    will be copied to the node for installation.
    """
    os.chdir(directory)

    if not os.path.exists("paradrop.yaml"):
        raise Exception("No paradrop.yaml file found in chute directory.")

    with open('paradrop.yaml', 'r') as source:
        config = yaml.safe_load(source)

    if 'name' not in config:
        click.echo('Chute name is not defined in paradrop.yaml.')
        return

    client = ctx.obj['client']
    with tempfile.TemporaryFile() as temp:
        tar = tarfile.open(fileobj=temp, mode="w")
        for dirName, subdirList, fileList in os.walk("."):
            for fname in fileList:
                path = os.path.join(dirName, fname)
                arcname = os.path.normpath(path)
                tar.add(path, arcname=arcname)
        tar.close()

        temp.seek(0)
        result = client.install_tar(temp, name=config['name'])
        ctx.invoke(watch_change_logs, change_id=result['change_id']) 
Example 70
Project: openhatch   Author: campbe13   File: deploy.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _build_egg():
    closest = closest_scrapy_cfg()
    os.chdir(os.path.dirname(closest))
    if not os.path.exists('setup.py'):
        settings = get_config().get('settings', 'default')
        _create_default_setup_py(settings=settings)
    d = tempfile.mkdtemp()
    f = tempfile.TemporaryFile(dir=d)
    check_call([sys.executable, 'setup.py', 'clean', '-a', 'bdist_egg', '-d', d], stdout=f)
    egg = glob.glob(os.path.join(d, '*.egg'))[0]
    return egg, d 
Example 71
Project: openhatch   Author: campbe13   File: feedexport.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def open(self, spider):
        return TemporaryFile(prefix='feed-') 
Example 72
Project: openhatch   Author: campbe13   File: request.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def make_tempfile(self):
        """
            Create a tempfile to store big request body.
            This API is not stable yet. A 'size' argument might be added.
        """
        return tempfile.TemporaryFile() 
Example 73
Project: deb-python-cassandra-driver   Author: openstack   File: test_types.py    Apache License 2.0 5 votes vote down vote up
def test_write_read_string(self):
        with tempfile.TemporaryFile() as f:
            value = u'test'
            write_string(f, value)
            f.seek(0)
            self.assertEqual(read_string(f), value) 
Example 74
Project: deb-python-cassandra-driver   Author: openstack   File: test_types.py    Apache License 2.0 5 votes vote down vote up
def test_write_read_longstring(self):
        with tempfile.TemporaryFile() as f:
            value = u'test'
            write_longstring(f, value)
            f.seek(0)
            self.assertEqual(read_longstring(f), value) 
Example 75
Project: deb-python-cassandra-driver   Author: openstack   File: test_types.py    Apache License 2.0 5 votes vote down vote up
def test_write_read_stringmap(self):
        with tempfile.TemporaryFile() as f:
            value = {'key': 'value'}
            write_stringmap(f, value)
            f.seek(0)
            self.assertEqual(read_stringmap(f), value) 
Example 76
Project: deb-python-cassandra-driver   Author: openstack   File: test_types.py    Apache License 2.0 5 votes vote down vote up
def test_write_read_inet(self):
        with tempfile.TemporaryFile() as f:
            value = ('192.168.1.1', 9042)
            write_inet(f, value)
            f.seek(0)
            self.assertEqual(read_inet(f), value)

        with tempfile.TemporaryFile() as f:
            value = ('2001:db8:0:f101::1', 9042)
            write_inet(f, value)
            f.seek(0)
            self.assertEqual(read_inet(f), value) 
Example 77
Project: jawfish   Author: war-and-code   File: cgi.py    MIT License 5 votes vote down vote up
def make_file(self, binary=None):
        """Overridable: return a readable & writable file.

        The file will be used as follows:
        - data is written to it
        - seek(0)
        - data is read from it

        The 'binary' argument is unused -- the file is always opened
        in binary mode.

        This version opens a temporary file for reading and writing,
        and immediately deletes (unlinks) it.  The trick (on Unix!) is
        that the file can still be used, but it can't be opened by
        another process, and it will automatically be deleted when it
        is closed or when the current process terminates.

        If you want a more permanent file, you derive a class which
        overrides this method.  If you want a visible temporary file
        that is nevertheless automatically deleted when the script
        terminates, try defining a __del__ method in a derived class
        which unlinks the temporary files you have created.

        """
        import tempfile
        return tempfile.TemporaryFile("w+b")



# Backwards Compatibility Classes
# =============================== 
Example 78
Project: jawfish   Author: war-and-code   File: cgi.py    MIT License 5 votes vote down vote up
def make_file(self, binary=None):
        """Overridable: return a readable & writable file.

        The file will be used as follows:
        - data is written to it
        - seek(0)
        - data is read from it

        The 'binary' argument is unused -- the file is always opened
        in binary mode.

        This version opens a temporary file for reading and writing,
        and immediately deletes (unlinks) it.  The trick (on Unix!) is
        that the file can still be used, but it can't be opened by
        another process, and it will automatically be deleted when it
        is closed or when the current process terminates.

        If you want a more permanent file, you derive a class which
        overrides this method.  If you want a visible temporary file
        that is nevertheless automatically deleted when the script
        terminates, try defining a __del__ method in a derived class
        which unlinks the temporary files you have created.

        """
        import tempfile
        return tempfile.TemporaryFile("w+b")



# Backwards Compatibility Classes
# =============================== 
Example 79
Project: razzy-spinner   Author: rafasashi   File: timit.py    GNU General Public License v3.0 5 votes vote down vote up
def wav(self, utterance, start=0, end=None):
        # nltk.chunk conflicts with the stdlib module 'chunk'
        wave = import_from_stdlib('wave')

        w = wave.open(self.open(utterance+'.wav'), 'rb')

        if end is None:
            end = w.getnframes()

        # Skip past frames before start, then read the frames we want
        w.readframes(start)
        frames = w.readframes(end-start)

        # Open a new temporary file -- the wave module requires
        # an actual file, and won't work w/ stringio. :(
        tf = tempfile.TemporaryFile()
        out = wave.open(tf, 'w')

        # Write the parameters & data to the new file.
        out.setparams(w.getparams())
        out.writeframes(frames)
        out.close()

        # Read the data back from the file, and return it.  The
        # file will automatically be deleted when we return.
        tf.seek(0)
        return tf.read() 
Example 80
Project: fs_image   Author: facebookincubator   File: test_send_fds_and_run.py    MIT License 4 votes vote down vote up
def test_send_fds(self):
        for sudo_args in [[], ['--sudo'], ['--sudo', '--sudo-arg', 'moo=cow']]:
            # Check basic wrapper execution, except for FD passing (we
            # pass 0 FDs), and `--no-set-listen-fds`.
            ret, out, err = _run([
                *sudo_args, '--', 'bash', '-c',
                'echo $SUDO_COMMAND ; echo $$ ; '
                    'printenv LISTEN_FDS LISTEN_PID ; exit 37',
            ])
            self.assertEqual([], _clean_err(err))
            self.assertEqual(37, ret)
            sudo, sh_pid, listen_fds, listen_pid = out.rstrip('\n').split('\n')
            self.assertEqual('0', listen_fds)
            self.assertEqual(sh_pid, listen_pid)
            self.assertEqual(bool(sudo), bool(sudo_args), f'{out} {sudo_args}')

            # Exercise `--no-set-listen-fds` and exit code 0.
            ret, out, err = _run([
                *sudo_args, '--no-set-listen-fds', '--', 'bash', '-c',
                'echo "$LISTEN_FDS/$LISTEN_PID"',
            ])
            self.assertEqual((0, '/\n', []), (ret, out, _clean_err(err)))

            # Exercise actual FD passing, both input and output
            with pipe() as (r_fd4, w_fd4), pipe() as (r_fd3, w_fd3), \
                    subprocess.Popen(['echo', 'hi-diddly-ho'], stdout=w_fd4), \
                    tempfile.TemporaryFile() as tf:
                w_fd4.close()  # or the Flanders cat might wait forever
                with subprocess.Popen(
                    ['cat'], stdin=r_fd3, stdout=tf.fileno(),
                ) as homer_proc:
                    try:
                        ret, out, err = _run([
                            *sudo_args,
                            '--fd', str(w_fd3.fileno()),
                            '--fd', str(r_fd4.fileno()),
                            '--', 'bash', '-c',
                            'echo "$LISTEN_FDS" ; cat <&4 ; echo doh >&3',
                        ])
                    finally:
                        w_fd3.close()  # or the Homer cat might wait forever
                self.assertEqual([], _clean_err(err))
                self.assertEqual('2\nhi-diddly-ho\n', out)
                self.assertEqual(0, ret)
                tf.seek(0)
                self.assertEqual(b'doh\n', tf.read())
                homer_proc.wait()