Python tempfile.tempdir() Examples

The following are 30 code examples of tempfile.tempdir(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tempfile , or try the search function .
Example #1
Source File: core.py    From pulsar with Apache License 2.0 6 votes vote down vote up
def __setup_object_store(self, conf):
        if "object_store_config_file" not in conf and "object_store_config" not in conf:
            self.object_store = None
            return

        config_obj_kwds = dict(
            file_path=conf.get("object_store_file_path", None),
            object_store_check_old_style=False,
            job_working_directory=conf.get("object_store_job_working_directory", None),
            new_file_path=conf.get("object_store_new_file_path", tempdir),
            umask=int(conf.get("object_store_umask", "0000")),
            jobs_directory=None,
        )
        config_dict = None
        if conf.get("object_store_config_file"):
            config_obj_kwds["object_store_config_file"] = conf['object_store_config_file']
        else:
            config_dict = conf["object_store_config"]

        object_store_config = Bunch(**config_obj_kwds)
        self.object_store = build_object_store_from_config(object_store_config, config_dict=config_dict) 
Example #2
Source File: jlock.py    From pylink with Apache License 2.0 6 votes vote down vote up
def __init__(self, serial_no):
        """Creates an instance of a ``JLock`` and populates the name.

        Note:
          This method may fail if there is no temporary directory in which to
          have the lockfile placed.

        Args:
          self (JLock): the ``JLock`` instance
          serial_no (int): the serial number of the J-Link

        Returns:
          ``None``
        """
        self.name = self.SERIAL_NAME_FMT.format(serial_no)
        self.acquired = False
        self.fd = None
        self.path = None
        self.path = os.path.join(tempfile.tempdir, self.name) 
Example #3
Source File: test_tempfile.py    From ironpython3 with Apache License 2.0 6 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,
            "TemporaryDirectory" : 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 #4
Source File: test_cache.py    From yatsm with MIT License 6 votes vote down vote up
def test_test_cache(mkdir_permissions):
    # Test when cache dir exists already
    path = mkdir_permissions(read=False, write=False)
    assert (False, False) == cache.test_cache(dict(cache_line_dir=path))

    path = mkdir_permissions(read=False, write=True)
    assert (False, True) == cache.test_cache(dict(cache_line_dir=path))

    path = mkdir_permissions(read=True, write=False)
    assert (True, False) == cache.test_cache(dict(cache_line_dir=path))

    path = mkdir_permissions(read=True, write=True)
    assert (True, True) == cache.test_cache(dict(cache_line_dir=path))

    # Test when cache dir doesn't exist
    tmp = os.path.join(tempfile.tempdir,
                       next(tempfile._get_candidate_names()) + '_yatsm')
    read_write = cache.test_cache(dict(cache_line_dir=tmp))
    os.removedirs(tmp)

    assert (True, True) == read_write 
Example #5
Source File: test_tempfile.py    From ironpython2 with Apache License 2.0 6 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 #6
Source File: test_image_repositoy.py    From me-ica with GNU Lesser General Public License v2.1 6 votes vote down vote up
def test_module_scope_is_updated_on_patch(expected_attrs):
  '''
  Patch should update the module's globals() on success
  '''
  from gooey.gui import image_repository
  testing_icons = ('config_icon.png', 'success_icon.png')
  try:
    # setup
    make_user_files(*testing_icons)
    old_icon = image_repository.config_icon
    # load up our new icon(s)
    image_repository.patch_images(tempfile.tempdir)
    new_icon = image_repository.config_icon
    assert old_icon != new_icon
  finally:
    cleanup_temp(*testing_icons)


# helpers 
Example #7
Source File: tool.py    From sequitur-g2p with GNU General Public License v2.0 5 votes vote down vote up
def addOptions(optparser):
    optparser.add_option(
        '-p', '--profile',
        help='Profile execution time and store result in FILE', metavar='FILE')
    optparser.add_option(
        '-R', '--resource-usage', action='store_true',
        help='Report resource usage execution time')
    optparser.add_option(
        '-Y', '--psyco', action='store_true',
        help='Use Psyco to speed up execution')
    optparser.add_option(
        '--tempdir',
        help='store temporary files in PATH', metavar='PATH') 
Example #8
Source File: _cache.py    From pipelines with Apache License 2.0 5 votes vote down vote up
def try_read_value_from_cache(cache_type: str, key: str) -> str:
    cache_file_path = Path(tempfile.tempdir) / cache_type / key
    if cache_file_path.exists():
        return cache_file_path.read_text()
    return None 
Example #9
Source File: tool.py    From sequitur-g2p with GNU General Public License v2.0 5 votes vote down vote up
def run(main, options, args):
    import sys

    if options.tempdir:
        import tempfile, os
        if os.path.isdir(options.tempdir):
            tempfile.tempdir = options.tempdir
        else:
            raise ValueError('path does not exist', options.tempdir)

    if options.resource_usage:
        import datetime, time
        startTime = datetime.datetime.now()
        startClock = time.clock()

    try:
        status = runMain(main, options, args)
    except UsageError:
        status = 1
        print("Try '%s --help'" % sys.argv[0], file=sys.stdout)

    if options.resource_usage:
        stopTime = datetime.datetime.now()
        stopClock = time.clock()
        print('elapsed time:   ', stopTime - startTime, file=sys.stderr)
        print('processor time: ', datetime.timedelta(seconds=stopClock - startClock), file=sys.stderr)

    sys.exit(status) 
Example #10
Source File: sandbox.py    From stopstalk-deployment with MIT License 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    pkg_resources.py31compat.makedirs(replacement, exist_ok=True)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example #11
Source File: sandbox.py    From rules_pip with MIT License 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    pkg_resources.py31compat.makedirs(replacement, exist_ok=True)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example #12
Source File: test_tempfile.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def _inside_empty_temp_dir():
    dir = tempfile.mkdtemp()
    try:
        with support.swap_attr(tempfile, 'tempdir', dir):
            yield
    finally:
        support.rmtree(dir) 
Example #13
Source File: _cache.py    From pipelines with Apache License 2.0 5 votes vote down vote up
def clear_cache(cache_type: str):
    cache_file_path = Path(tempfile.tempdir) / cache_type
    if cache_file_path.exists():
        shutil.rmtree(cache_file_path) 
Example #14
Source File: __init__.py    From catalyst with Apache License 2.0 5 votes vote down vote up
def _():
        import atexit
        import tempfile

        tempfile.tempdir = tempdir = tempfile.mkdtemp()

        @atexit.register
        def cleanup_tempdir():
            import shutil
            shutil.rmtree(tempdir) 
Example #15
Source File: test_shaft_element.py    From ross with MIT License 5 votes vote down vote up
def test_save_load(tim, tap_tim):
    file = Path(tempdir) / "tim.toml"
    tim.save(file)
    tim_loaded = ShaftElement.load(file)
    assert tim == tim_loaded

    file = Path(tempdir) / "tap_tim.toml"
    tap_tim.save(file)
    tap_tim_loaded = ShaftElement.load(file)
    assert tap_tim == tap_tim_loaded 
Example #16
Source File: test_rotor_assembly.py    From ross with MIT License 5 votes vote down vote up
def test_save_load(rotor8):
    file = Path(tempdir) / "rotor8.toml"
    rotor8.save(file)
    rotor8_loaded = Rotor.load(file)

    rotor8 == rotor8_loaded 
Example #17
Source File: test_disk_element.py    From ross with MIT License 5 votes vote down vote up
def test_save_load(disk, disk_from_geometry):
    file = Path(tempdir) / "disk.toml"
    disk.save(file)
    disk_loaded = DiskElement.load(file)
    assert disk == disk_loaded 
Example #18
Source File: test_point_mass.py    From ross with MIT License 5 votes vote down vote up
def test_save_load():
    p = PointMass(n=0, m=10.0, tag="pointmass")
    file = Path(tempdir) / "point_mass.toml"
    p.save(file)
    p_loaded = p.load(file)

    assert p == p_loaded 
Example #19
Source File: sandbox.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    pkg_resources.py31compat.makedirs(replacement, exist_ok=True)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example #20
Source File: build_deps.py    From build-calibre with GNU General Public License v3.0 5 votes vote down vote up
def init_env(deps=all_deps):
    dest_dir = PREFIX
    ensure_clear_dir(dest_dir)
    tdir = tempfile.tempdir if iswindows else os.path.join(tempfile.gettempdir(), 't')
    ensure_clear_dir(tdir)
    set_tdir(tdir)
    install_pkgs(deps, dest_dir)
    return dest_dir 
Example #21
Source File: sandbox.py    From scylla with Apache License 2.0 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    pkg_resources.py31compat.makedirs(replacement, exist_ok=True)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example #22
Source File: job.py    From cumulus with Apache License 2.0 5 votes vote down vote up
def next(self, job_queue_status):

        error = False
        for output in self.job.get('output', []):
            if 'errorRegEx' in output and output['errorRegEx']:
                stdout_file = '%s-%s.o%s' % (self.job['name'],
                                             self.job['_id'],
                                             self.job['queueJobId'])

                stderr_file = '%s-%s.o%s' % (self.job['name'],
                                             self.job['_id'],
                                             self.job['queueJobId'])
                variables = {
                    'stdout': stdout_file,
                    'stderr': stderr_file
                }

                tmp_path = None
                try:
                    path = Template(output['path']).render(**variables)
                    tmp_path = os.path.join(tempfile.tempdir, path)
                    path = os.path.join(self.job['dir'], path)
                    self.conn.get(path, localpath=tmp_path)
                    error_regex = re.compile(output['errorRegEx'])
                    with open(tmp_path, 'r') as fp:
                        for line in fp:
                            if error_regex.match(line):
                                error = True
                                break
                finally:
                    if tmp_path and os.path.exists(tmp_path):
                        os.remove(tmp_path)

            if error:
                break

        if error:
            return Error(self)

        return self 
Example #23
Source File: test_tempfile.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_non_directory(self):
        with _inside_empty_temp_dir():
            tempdir = os.path.join(tempfile.tempdir, 'file')
            open(tempdir, 'wb').close()
            with support.swap_attr(tempfile, 'tempdir', tempdir):
                with self.assertRaises((NotADirectoryError, FileNotFoundError)):
                    self.make_temp() 
Example #24
Source File: test_tempfile.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_nonexisting_directory(self):
        with _inside_empty_temp_dir():
            tempdir = os.path.join(tempfile.tempdir, 'nonexistent')
            with support.swap_attr(tempfile, 'tempdir', tempdir):
                with self.assertRaises(FileNotFoundError):
                    self.make_temp() 
Example #25
Source File: test_tempfile.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_read_only_directory(self):
        with _inside_empty_temp_dir():
            oldmode = mode = os.stat(tempfile.tempdir).st_mode
            mode &= ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
            os.chmod(tempfile.tempdir, mode)
            try:
                if os.access(tempfile.tempdir, os.W_OK):
                    self.skipTest("can't set the directory read-only")
                with self.assertRaises(PermissionError):
                    self.make_temp()
                self.assertEqual(os.listdir(tempfile.tempdir), [])
            finally:
                os.chmod(tempfile.tempdir, oldmode) 
Example #26
Source File: test_tempfile.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def _inside_empty_temp_dir():
    dir = tempfile.mkdtemp()
    try:
        with support.swap_attr(tempfile, 'tempdir', dir):
            yield
    finally:
        support.rmtree(dir) 
Example #27
Source File: test_tempfile.py    From Fluid-Designer with GNU General Public License v3.0 5 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,
            "gettempprefixb" : 1,
            "gettempdir" : 1,
            "gettempdirb" : 1,
            "tempdir" : 1,
            "template" : 1,
            "SpooledTemporaryFile" : 1,
            "TemporaryDirectory" : 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 #28
Source File: sandbox.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    pkg_resources.py31compat.makedirs(replacement, exist_ok=True)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example #29
Source File: sandbox.py    From ImageFusion with MIT License 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    if not os.path.isdir(replacement):
        os.makedirs(replacement)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example #30
Source File: test_tempfile.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_read_only_directory(self):
        with _inside_empty_temp_dir():
            oldmode = mode = os.stat(tempfile.tempdir).st_mode
            mode &= ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
            os.chmod(tempfile.tempdir, mode)
            try:
                if os.access(tempfile.tempdir, os.W_OK):
                    self.skipTest("can't set the directory read-only")
                with self.assertRaises(PermissionError):
                    self.make_temp()
                self.assertEqual(os.listdir(tempfile.tempdir), [])
            finally:
                os.chmod(tempfile.tempdir, oldmode)