Python tempfile.gettempdir() Examples

The following are code examples for showing how to use tempfile.gettempdir(). 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: alfred-yubikey-otp   Author: robertoriv   File: update.py    MIT License 6 votes vote down vote up
def download_workflow(url):
    """Download workflow at ``url`` to a local temporary file.

    :param url: URL to .alfredworkflow file in GitHub repo
    :returns: path to downloaded file

    """
    filename = url.split('/')[-1]

    if (not filename.endswith('.alfredworkflow') and
            not filename.endswith('.alfred3workflow')):
        raise ValueError('attachment not a workflow: {0}'.format(filename))

    local_path = os.path.join(tempfile.gettempdir(), filename)

    wf().logger.debug(
        'downloading updated workflow from `%s` to `%s` ...', url, local_path)

    response = web.get(url)

    with open(local_path, 'wb') as output:
        output.write(response.content)

    return local_path 
Example 3
Project: pyblish-win   Author: pyblish   File: webbrowser.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _find_grail_rc(self):
        import glob
        import pwd
        import socket
        import tempfile
        tempdir = os.path.join(tempfile.gettempdir(),
                               ".grail-unix")
        user = pwd.getpwuid(os.getuid())[0]
        filename = os.path.join(tempdir, user + "-*")
        maybes = glob.glob(filename)
        if not maybes:
            return None
        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        for fn in maybes:
            # need to PING each one until we find one that's live
            try:
                s.connect(fn)
            except socket.error:
                # no good; attempt to clean it out, but don't fail:
                try:
                    os.unlink(fn)
                except IOError:
                    pass
            else:
                return s 
Example 4
Project: pyblish-win   Author: pyblish   File: test_filecmp.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def setUp(self):
        tmpdir = tempfile.gettempdir()
        self.dir = os.path.join(tmpdir, 'dir')
        self.dir_same = os.path.join(tmpdir, 'dir-same')
        self.dir_diff = os.path.join(tmpdir, 'dir-diff')
        self.caseinsensitive = os.path.normcase('A') == os.path.normcase('a')
        data = 'Contents of file go here.\n'
        for dir in [self.dir, self.dir_same, self.dir_diff]:
            shutil.rmtree(dir, True)
            os.mkdir(dir)
            if self.caseinsensitive and dir is self.dir_same:
                fn = 'FiLe'     # Verify case-insensitive comparison
            else:
                fn = 'file'
            output = open(os.path.join(dir, fn), 'w')
            output.write(data)
            output.close()

        output = open(os.path.join(self.dir_diff, 'file2'), 'w')
        output.write('An extra file.\n')
        output.close() 
Example 5
Project: pyblish-win   Author: pyblish   File: test_tempfile.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def do_create(self, dir=None, pre="", suf=""):
        if dir is None:
            dir = tempfile.gettempdir()
        try:
            (fd, name) = tempfile.mkstemp(dir=dir, prefix=pre, suffix=suf)
            (ndir, nbase) = os.path.split(name)
            adir = os.path.abspath(dir)
            self.assertEqual(adir, ndir,
                "Directory '%s' incorrectly returned as '%s'" % (adir, ndir))
        except:
            self.failOnException("mkstemp")

        try:
            self.nameCheck(name, dir, pre, suf)
        finally:
            os.close(fd)
            os.unlink(name) 
Example 6
Project: pyblish-win   Author: pyblish   File: test_subprocess.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_cwd(self):
        tmpdir = tempfile.gettempdir()
        # We cannot use os.path.realpath to canonicalize the path,
        # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
        cwd = os.getcwd()
        os.chdir(tmpdir)
        tmpdir = os.getcwd()
        os.chdir(cwd)
        p = subprocess.Popen([sys.executable, "-c",
                          'import sys,os;'
                          'sys.stdout.write(os.getcwd())'],
                         stdout=subprocess.PIPE,
                         cwd=tmpdir)
        self.addCleanup(p.stdout.close)
        normcase = os.path.normcase
        self.assertEqual(normcase(p.stdout.read()), normcase(tmpdir)) 
Example 7
Project: pyblish-win   Author: pyblish   File: test_bsddb3.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_main():
    from bsddb import db
    from bsddb.test import test_all
    test_all.set_test_path_prefix(os.path.join(tempfile.gettempdir(),
                                 'z-test_bsddb3-%s' %
                                 os.getpid()))
    # Please leave this print in, having this show up in the buildbots
    # makes diagnosing problems a lot easier.
    print >>sys.stderr, db.DB_VERSION_STRING
    print >>sys.stderr, 'Test path prefix: ', test_all.get_test_path_prefix()
    try:
        run_unittest(test_all.suite(module_prefix='bsddb.test.',
                                    timing_check=TimingCheck))
    finally:
        # The only reason to remove db_home is in case if there is an old
        # one lying around.  This might be by a different user, so just
        # ignore errors.  We should always make a unique name now.
        try:
            test_all.remove_test_path_directory()
        except:
            pass 
Example 8
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: update.py    MIT License 6 votes vote down vote up
def download_workflow(url):
    """Download workflow at ``url`` to a local temporary file.

    :param url: URL to .alfredworkflow file in GitHub repo
    :returns: path to downloaded file

    """
    filename = url.split('/')[-1]

    if (not filename.endswith('.alfredworkflow') and
            not filename.endswith('.alfred3workflow')):
        raise ValueError('attachment not a workflow: {0}'.format(filename))

    local_path = os.path.join(tempfile.gettempdir(), filename)

    wf().logger.debug(
        'downloading updated workflow from `%s` to `%s` ...', url, local_path)

    response = web.get(url)

    with open(local_path, 'wb') as output:
        output.write(response.content)

    return local_path 
Example 9
Project: neural-fingerprinting   Author: StephanZheng   File: utils_mnist.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def maybe_download_mnist_file(file_name, datadir=None, force=False):
    try:
        from urllib.parse import urljoin
        from urllib.request import urlretrieve
    except ImportError:
        from urlparse import urljoin
        from urllib import urlretrieve

    if not datadir:
        datadir = tempfile.gettempdir()
    dest_file = os.path.join(datadir, file_name)

    if force or not os.path.isfile(file_name):
        url = urljoin('http://yann.lecun.com/exdb/mnist/', file_name)
        urlretrieve(url, dest_file)
    return dest_file 
Example 10
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: build.py    Apache License 2.0 6 votes vote down vote up
def default_ccache_dir() -> str:
    """:return: ccache directory for the current platform"""
    # Share ccache across containers
    if 'CCACHE_DIR' in os.environ:
        ccache_dir = os.path.realpath(os.environ['CCACHE_DIR'])
        try:
            os.makedirs(ccache_dir, exist_ok=True)
            return ccache_dir
        except PermissionError:
            logging.info('Unable to make dirs at %s, falling back to local temp dir', ccache_dir)
    # In osx tmpdir is not mountable by default
    import platform
    if platform.system() == 'Darwin':
        ccache_dir = "/tmp/_mxnet_ccache"
        os.makedirs(ccache_dir, exist_ok=True)
        return ccache_dir
    return os.path.join(tempfile.gettempdir(), "ci_ccache") 
Example 11
Project: CyberTK-Self   Author: CyberTKR   File: LineApi.py    GNU General Public License v2.0 6 votes vote down vote up
def sendImageWithUrl(self, to_, url):
        """Send a image with given image url

        :param url: image url to send
        """
        path = '%s/pythonLine-%1.data' % (tempfile.gettempdir(), randint(0, 9))


        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download image failure.')

        try:
            self.sendImage(to_, path)
        except Exception as e:
            raise e 
Example 12
Project: alfred-urban-dictionary   Author: xilopaint   File: update.py    MIT License 6 votes vote down vote up
def download_workflow(url):
    """Download workflow at ``url`` to a local temporary file.

    :param url: URL to .alfredworkflow file in GitHub repo
    :returns: path to downloaded file

    """
    filename = url.split('/')[-1]

    if (not filename.endswith('.alfredworkflow') and
            not filename.endswith('.alfred3workflow')):
        raise ValueError('attachment not a workflow: {0}'.format(filename))

    local_path = os.path.join(tempfile.gettempdir(), filename)

    wf().logger.debug(
        'downloading updated workflow from `%s` to `%s` ...', url, local_path)

    response = web.get(url)

    with open(local_path, 'wb') as output:
        output.write(response.content)

    return local_path 
Example 13
Project: AshsSDK   Author: thehappydinoa   File: artifact_exporter.py    MIT License 6 votes vote down vote up
def zip_folder(folder_path):
    """
    Zip the entire folder and return a file to the zip. Use this inside
    a "with" statement to cleanup the zipfile after it is used.

    :param folder_path:
    :return: Name of the zipfile
    """

    filename = os.path.join(
        tempfile.gettempdir(), "data-" + uuid.uuid4().hex)

    zipfile_name = make_zip(filename, folder_path)
    try:
        yield zipfile_name
    finally:
        if os.path.exists(zipfile_name):
            os.remove(zipfile_name) 
Example 14
Project: nlimb   Author: cbschaff   File: logger.py    MIT License 6 votes vote down vote up
def configure(dir=None, format_strs=None):
    if dir is None:
        dir = os.getenv('OPENAI_LOGDIR')
    if dir is None:
        dir = osp.join(tempfile.gettempdir(),
            datetime.datetime.now().strftime("openai-%Y-%m-%d-%H-%M-%S-%f"))
    assert isinstance(dir, str)
    os.makedirs(dir, exist_ok=True)

    if format_strs is None:
        strs = os.getenv('OPENAI_LOG_FORMAT')
        format_strs = strs.split(',') if strs else LOG_OUTPUT_FORMATS
    output_formats = [make_output_format(f, dir) for f in format_strs]

    Logger.CURRENT = Logger(dir=dir, output_formats=output_formats)
    log('Logging to %s'%dir) 
Example 15
Project: PyBoof   Author: lessthanoptimal   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def init_memmap(size_mb=2):
    """
    Call to enable use of memory mapped files for quick communication between Python and Java.  This
    faster communication method requires specialized code so is only used when large amounts of memory
    is being transferred.

    :param size_mb: Size of the memory mapped file in megabytes
    :type size_mb: int
    """
    global mmap_size, mmap_file
    import tempfile
    mmap_path = os.path.join(tempfile.gettempdir(),"pyboof_mmap")
    mmap_size = size_mb * 1024 * 1024
    gateway.jvm.pyboof.PyBoofEntryPoint.initializeMmap(mmap_path, size_mb)
    # Open file in read,write,binary mode
    mmap_fid = open(mmap_path, "r+b")
    mmap_file = mmap.mmap(mmap_fid.fileno(), length=0, flags=mmap.MAP_SHARED,
                          prot=mmap.PROT_READ | mmap.PROT_WRITE) 
Example 16
Project: wuy   Author: manatlan   File: freeze.py    GNU General Public License v2.0 6 votes vote down vote up
def build(path,inConsole=False,addWeb=False):
    params=[path,"--noupx","--onefile"]

    if not inConsole:
        params.append( "--noconsole")
    
    web=os.path.join( os.path.dirname(path), "web" )
    if addWeb and os.path.isdir(web):
        sep = (os.name == 'nt') and ";" or ":"
        params.append("--add-data=%s%sweb" % (web,sep))

    temp=os.path.join(tempfile.gettempdir(),".build")
    params.append( "--workpath" )
    params.append( temp )

    params.append( "--distpath" )
    params.append( os.path.dirname(path) )

    print( "PYINSTALLER:",params )
    pyi.run( params ) 
Example 17
Project: fine-lm   Author: akzaidi   File: cloud_mlengine.py    MIT License 6 votes vote down vote up
def _tar_and_copy(src_dir, target_dir):
  """Tar and gzip src_dir and copy to GCS target_dir."""
  src_dir = src_dir.rstrip("/")
  target_dir = target_dir.rstrip("/")
  tmp_dir = tempfile.gettempdir().rstrip("/")
  src_base = os.path.basename(src_dir)
  cloud.shell_run(
      "tar -zcf {tmp_dir}/{src_base}.tar.gz -C {src_dir} .",
      src_dir=src_dir,
      src_base=src_base,
      tmp_dir=tmp_dir)
  final_destination = "%s/%s.tar.gz" % (target_dir, src_base)
  cloud.shell_run(
      ("gsutil cp {tmp_dir}/{src_base}.tar.gz "
       "{final_destination}"),
      tmp_dir=tmp_dir,
      src_base=src_base,
      final_destination=final_destination)
  return final_destination 
Example 18
Project: fine-lm   Author: akzaidi   File: cloud_mlengine.py    MIT License 6 votes vote down vote up
def tar_and_copy_usr_dir(usr_dir, train_dir):
  """Package, tar, and copy usr_dir to GCS train_dir."""
  tf.logging.info("Tarring and pushing t2t_usr_dir.")
  usr_dir = os.path.abspath(os.path.expanduser(usr_dir))
  # Copy usr dir to a temp location
  top_dir = os.path.join(tempfile.gettempdir(), "t2t_usr_container")
  tmp_usr_dir = os.path.join(top_dir, usr_dir_lib.INTERNAL_USR_DIR_PACKAGE)
  shutil.rmtree(top_dir, ignore_errors=True)
  shutil.copytree(usr_dir, tmp_usr_dir)
  # Insert setup.py if one does not exist
  top_setup_fname = os.path.join(top_dir, "setup.py")
  setup_file_str = get_setup_file(
      name="DummyUsrDirPackage",
      packages=get_requirements(usr_dir)
  )
  with tf.gfile.Open(top_setup_fname, "w") as f:
    f.write(setup_file_str)
  usr_tar = _tar_and_copy(top_dir, train_dir)
  return usr_tar 
Example 19
Project: lirpg   Author: Hwhitetooth   File: logger.py    MIT License 6 votes vote down vote up
def configure(dir=None, format_strs=None):
    if dir is None:
        dir = os.getenv('OPENAI_LOGDIR')
    if dir is None:
        dir = osp.join(tempfile.gettempdir(),
            datetime.datetime.now().strftime("openai-%Y-%m-%d-%H-%M-%S-%f"))
    assert isinstance(dir, str)
    os.makedirs(dir, exist_ok=True)

    if format_strs is None:
        strs = os.getenv('OPENAI_LOG_FORMAT')
        format_strs = strs.split(',') if strs else LOG_OUTPUT_FORMATS
    output_formats = [make_output_format(f, dir) for f in format_strs]

    Logger.CURRENT = Logger(dir=dir, output_formats=output_formats)
    log('Logging to %s'%dir) 
Example 20
Project: calmjs   Author: calmjs   File: test_toolchain.py    GNU General Public License v2.0 6 votes vote down vote up
def test_toolchain_standard_not_implemented(self):
        spec = Spec()

        with self.assertRaises(NotImplementedError):
            self.toolchain(spec)

        with self.assertRaises(NotImplementedError):
            self.toolchain.assemble(spec)

        with self.assertRaises(NotImplementedError):
            self.toolchain.link(spec)

        # Check that the build_dir is set on the spec based on tempfile
        self.assertTrue(spec['build_dir'].startswith(
            realpath(tempfile.gettempdir())))
        # Also that it got deleted properly.
        self.assertFalse(exists(spec['build_dir'])) 
Example 21
Project: ngo-addons-backport   Author: camptocamp   File: http.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def session_path():
    try:
        import pwd
        username = pwd.getpwuid(os.geteuid()).pw_name
    except ImportError:
        try:
            username = getpass.getuser()
        except Exception:
            username = "unknown"
    path = os.path.join(tempfile.gettempdir(), "oe-sessions-" + username)
    try:
        os.mkdir(path, 0700)
    except OSError as exc:
        if exc.errno == errno.EEXIST:
            # directory exists: ensure it has the correct permissions
            # this will fail if the directory is not owned by the current user
            os.chmod(path, 0700)
        else:
            raise
    return path 
Example 22
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 23
Project: ngo-addons-backport   Author: camptocamp   File: functions.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def GetAFileName():
    oFileDialog=None
    iAccept=None
    sPath=""
    InitPath=""
    oUcb=None
    oFileDialog = createUnoService("com.sun.star.ui.dialogs.FilePicker")
    oUcb = createUnoService("com.sun.star.ucb.SimpleFileAccess")
    oFileDialog.appendFilter("OpenERP Report File","*.sxw")
    oFileDialog.setCurrentFilter("OpenERP Report File")
    if InitPath == "":
        InitPath =tempfile.gettempdir()
    #End If
    if oUcb.exists(InitPath):
        oFileDialog.setDisplayDirectory(InitPath)
    #End If
    iAccept = oFileDialog.execute()
    if iAccept == 1:
        sPath = oFileDialog.Files[0]
    oFileDialog.dispose()
    return sPath



# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: 
Example 24
Project: HardRLWithYoutube   Author: MaxSobolMark   File: logger.py    MIT License 6 votes vote down vote up
def configure(dir=None, format_strs=None):
    if dir is None:
        dir = os.getenv('OPENAI_LOGDIR')
    if dir is None:
        dir = osp.join(tempfile.gettempdir(),
            datetime.datetime.now().strftime("openai-%Y-%m-%d-%H-%M-%S-%f"))
    assert isinstance(dir, str)
    os.makedirs(dir, exist_ok=True)

    log_suffix = ''
    from mpi4py import MPI
    rank = MPI.COMM_WORLD.Get_rank()
    if rank > 0:
        log_suffix = "-rank%03i" % rank

    if format_strs is None:
        if rank == 0:
            format_strs = os.getenv('OPENAI_LOG_FORMAT', 'stdout,log,csv').split(',')
        else:
            format_strs = os.getenv('OPENAI_LOG_FORMAT_MPI', 'log').split(',')
    format_strs = filter(None, format_strs)
    output_formats = [make_output_format(f, dir, log_suffix) for f in format_strs]

    Logger.CURRENT = Logger(dir=dir, output_formats=output_formats)
    log('Logging to %s'%dir) 
Example 25
Project: HardRLWithYoutube   Author: MaxSobolMark   File: mnist_env.py    MIT License 6 votes vote down vote up
def __init__(
            self,
            seed=0,
            episode_len=None,
            no_images=None
    ):
        from tensorflow.examples.tutorials.mnist import input_data
        # we could use temporary directory for this with a context manager and 
        # TemporaryDirecotry, but then each test that uses mnist would re-download the data
        # this way the data is not cleaned up, but we only download it once per machine
        mnist_path = osp.join(tempfile.gettempdir(), 'MNIST_data')
        with filelock.FileLock(mnist_path + '.lock'):
           self.mnist = input_data.read_data_sets(mnist_path)

        self.np_random = np.random.RandomState()
        self.np_random.seed(seed)

        self.observation_space = Box(low=0.0, high=1.0, shape=(28,28,1))
        self.action_space = Discrete(10)
        self.episode_len = episode_len
        self.time = 0
        self.no_images = no_images

        self.train_mode()
        self.reset() 
Example 26
Project: ddpg-curiosity-and-multi-criteria-her   Author: CDMCH   File: logger.py    MIT License 6 votes vote down vote up
def configure(dir=None, format_strs=None):
    if dir is None:
        dir = os.getenv('OPENAI_LOGDIR')
    if dir is None:
        dir = osp.join(tempfile.gettempdir(),
            datetime.datetime.now().strftime("openai-%Y-%m-%d-%H-%M-%S-%f"))
    assert isinstance(dir, str)
    os.makedirs(dir, exist_ok=True)

    log_suffix = ''
    from mpi4py import MPI
    rank = MPI.COMM_WORLD.Get_rank()
    if rank > 0:
        log_suffix = "-rank%03i" % rank

    if format_strs is None:
        if rank == 0:
            format_strs = os.getenv('OPENAI_LOG_FORMAT', 'stdout,log,csv').split(',')
        else:
            format_strs = os.getenv('OPENAI_LOG_FORMAT_MPI', 'log').split(',')
    format_strs = filter(None, format_strs)
    output_formats = [make_output_format(f, dir, log_suffix) for f in format_strs]

    Logger.CURRENT = Logger(dir=dir, output_formats=output_formats)
    log('Logging to %s'%dir) 
Example 27
Project: ddpg-curiosity-and-multi-criteria-her   Author: CDMCH   File: mnist_env.py    MIT License 6 votes vote down vote up
def __init__(
            self,
            seed=0,
            episode_len=None,
            no_images=None
    ):
        from tensorflow.examples.tutorials.mnist import input_data
        # we could use temporary directory for this with a context manager and 
        # TemporaryDirecotry, but then each test that uses mnist would re-download the data
        # this way the data is not cleaned up, but we only download it once per machine
        mnist_path = osp.join(tempfile.gettempdir(), 'MNIST_data')
        with filelock.FileLock(mnist_path + '.lock'):
           self.mnist = input_data.read_data_sets(mnist_path)

        self.np_random = np.random.RandomState()
        self.np_random.seed(seed)

        self.observation_space = Box(low=0.0, high=1.0, shape=(28,28,1))
        self.action_space = Discrete(10)
        self.episode_len = episode_len
        self.time = 0
        self.no_images = no_images

        self.train_mode()
        self.reset() 
Example 28
Project: invenio-oaiharvester   Author: inveniosoftware   File: utils.py    GNU General Public License v2.0 6 votes vote down vote up
def check_or_create_dir(output_dir):
    """Check whether the directory exists, and creates it if not.

    :param output_dir: The directory where the output should be sent.
    :return:
    """
    default = os.path.join(
        current_app.config["OAIHARVESTER_WORKDIR"] or tempfile.gettempdir(),
        "oaiharvester"
    )
    path = os.path.join(default, output_dir)

    if not os.path.exists(path):
        os.makedirs(path)

    return path 
Example 29
Project: dj-wkhtmltopdf   Author: dhanababum   File: utils.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, **kwargs):
        """
        By default it will search django core settings,
        if wkhtmltopdf not found there it will add that command.
        :param kwargs:
        It may contains the html and context,
        html object is model and context of view
        :type kwargs: Dictionary
        :returns: None
        """
        tempfile.tempdir = '/tmp/'
        self.tmp_dir = tempfile.gettempdir()
        self.html = kwargs.get('html')
        self.context = kwargs.get('context')
        self.command = []
        self.code_format = "utf-8"
        if hasattr(settings, "WKHTML_TO_PDF_CMD") and isinstance(settings.WKHTML_TO_PDF_CMD, str):
            self.command = [settings.WKHTML_TO_PDF_CMD] 
Example 30
Project: keras-bert   Author: CyberZHG   File: test_bert.py    MIT License 6 votes vote down vote up
def test_task_embed(self):
        inputs, outputs = get_model(
            token_num=20,
            embed_dim=12,
            head_num=3,
            transformer_num=2,
            use_task_embed=True,
            task_num=10,
            training=False,
            dropout_rate=0.0,
        )
        model = keras.models.Model(inputs, outputs)
        model_path = os.path.join(tempfile.gettempdir(), 'keras_bert_%f.h5' % np.random.random())
        model.save(model_path)
        model = keras.models.load_model(
            model_path,
            custom_objects=get_custom_objects(),
        )
        model.summary(line_length=200) 
Example 31
Project: gist-alfred   Author: danielecook   File: update.py    MIT License 6 votes vote down vote up
def retrieve_download(dl):
    """Saves a download to a temporary file and returns path.

    .. versionadded: 1.37

    Args:
        url (unicode): URL to .alfredworkflow file in GitHub repo

    Returns:
        unicode: path to downloaded file

    """
    if not match_workflow(dl.filename):
        raise ValueError('attachment not a workflow: ' + dl.filename)

    path = os.path.join(tempfile.gettempdir(), dl.filename)
    wf().logger.debug('downloading update from '
                      '%r to %r ...', dl.url, path)

    r = web.get(dl.url)
    r.raise_for_status()

    r.save_to_path(path)

    return path 
Example 32
Project: mlbv   Author: kmac   File: util.py    GNU General Public License v3.0 5 votes vote down vote up
def get_tempdir():
    """Create a directory for ourselves in the system tempdir."""
    tempdir = config.CONFIG.parser.get('tempdir', None)
    if tempdir:
        if '<timestamp>' in tempdir:
            tempdir = tempdir.replace('<timestamp>', time.strftime('%Y-%m-%d-%H%M'))
    else:
        script_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
        tempdir = os.path.join(tempfile.gettempdir(), script_name)
    if not os.path.exists(tempdir):
        os.makedirs(tempdir)
    return tempdir 
Example 33
Project: pyblish-win   Author: pyblish   File: test_filecmp.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.name = test_support.TESTFN
        self.name_same = test_support.TESTFN + '-same'
        self.name_diff = test_support.TESTFN + '-diff'
        data = 'Contents of file go here.\n'
        for name in [self.name, self.name_same, self.name_diff]:
            output = open(name, 'w')
            output.write(data)
            output.close()

        output = open(self.name_diff, 'a+')
        output.write('An extra line.\n')
        output.close()
        self.dir = tempfile.gettempdir() 
Example 34
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, dir=None, pre="", suf="", bin=1):
        if dir is None:
            dir = tempfile.gettempdir()
        try:
            file = self.mkstemped(dir, pre, suf, bin)
        except:
            self.failOnException("_mkstemp_inner")

        self.nameCheck(file.name, dir, pre, suf)
        return file 
Example 35
Project: pyblish-win   Author: pyblish   File: test_tempfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_directory_exists(self):
        # gettempdir returns a directory which exists

        dir = tempfile.gettempdir()
        self.assertTrue(os.path.isabs(dir) or dir == os.curdir,
                     "%s is not an absolute path" % dir)
        self.assertTrue(os.path.isdir(dir),
                     "%s is not a directory" % dir) 
Example 36
Project: pyblish-win   Author: pyblish   File: test_tempfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_directory_writable(self):
        # gettempdir returns a directory writable by the user

        # sneaky: just instantiate a NamedTemporaryFile, which
        # defaults to writing into the directory returned by
        # gettempdir.
        try:
            file = tempfile.NamedTemporaryFile()
            file.write("blat")
            file.close()
        except:
            self.failOnException("create file in %s" % tempfile.gettempdir()) 
Example 37
Project: pyblish-win   Author: pyblish   File: test_tempfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_same_thing(self):
        # gettempdir always returns the same object
        a = tempfile.gettempdir()
        b = tempfile.gettempdir()

        self.assertTrue(a is b) 
Example 38
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, dir=None, pre="", suf=""):
        if dir is None:
            dir = tempfile.gettempdir()
        try:
            name = tempfile.mkdtemp(dir=dir, prefix=pre, suffix=suf)
        except:
            self.failOnException("mkdtemp")

        try:
            self.nameCheck(name, dir, pre, suf)
            return name
        except:
            os.rmdir(name)
            raise 
Example 39
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, max_size=0, dir=None, pre="", suf=""):
        if dir is None:
            dir = tempfile.gettempdir()
        try:
            file = tempfile.SpooledTemporaryFile(max_size=max_size, dir=dir, prefix=pre, suffix=suf)
        except:
            self.failOnException("SpooledTemporaryFile")

        return file 
Example 40
Project: pyblish-win   Author: pyblish   File: test_httpservers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        BaseTestCase.setUp(self)
        self.cwd = os.getcwd()
        basetempdir = tempfile.gettempdir()
        os.chdir(basetempdir)
        self.data = 'We are the knights who say Ni!'
        self.tempdir = tempfile.mkdtemp(dir=basetempdir)
        self.tempdir_name = os.path.basename(self.tempdir)
        temp = open(os.path.join(self.tempdir, 'test'), 'wb')
        temp.write(self.data)
        temp.close() 
Example 41
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: bccache.py    Apache License 2.0 5 votes vote down vote up
def _get_default_cache_dir(self):
        tmpdir = tempfile.gettempdir()

        # On windows the temporary directory is used specific unless
        # explicitly forced otherwise.  We can just use that.
        if os.name == 'nt':
            return tmpdir
        if not hasattr(os, 'getuid'):
            raise RuntimeError('Cannot determine safe temp directory.  You '
                               'need to explicitly provide one.')

        dirname = '_jinja2-cache-%d' % os.getuid()
        actual_dir = os.path.join(tmpdir, dirname)
        try:
            os.mkdir(actual_dir, stat.S_IRWXU) # 0o700
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise

        actual_dir_stat = os.lstat(actual_dir)
        if actual_dir_stat.st_uid != os.getuid() \
                or not stat.S_ISDIR(actual_dir_stat.st_mode) \
                or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
            raise RuntimeError('Temporary directory \'%s\' has an incorrect '
	                       'owner, permissions, or type.' % actual_dir)

        return actual_dir 
Example 42
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: bccache.py    Apache License 2.0 5 votes vote down vote up
def _get_default_cache_dir(self):
        tmpdir = tempfile.gettempdir()

        # On windows the temporary directory is used specific unless
        # explicitly forced otherwise.  We can just use that.
        if os.name == 'nt':
            return tmpdir
        if not hasattr(os, 'getuid'):
            raise RuntimeError('Cannot determine safe temp directory.  You '
                               'need to explicitly provide one.')

        dirname = '_jinja2-cache-%d' % os.getuid()
        actual_dir = os.path.join(tmpdir, dirname)
        try:
            os.mkdir(actual_dir, stat.S_IRWXU) # 0o700
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise

        actual_dir_stat = os.lstat(actual_dir)
        if actual_dir_stat.st_uid != os.getuid() \
                or not stat.S_ISDIR(actual_dir_stat.st_mode) \
                or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
            raise RuntimeError('Temporary directory \'%s\' has an incorrect '
	                       'owner, permissions, or type.' % actual_dir)

        return actual_dir 
Example 43
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: sessions.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, path=None, filename_template='werkzeug_%s.sess',
                 session_class=None, renew_missing=False, mode=0o644):
        SessionStore.__init__(self, session_class)
        if path is None:
            path = tempfile.gettempdir()
        self.path = path
        if isinstance(filename_template, text_type) and PY2:
            filename_template = filename_template.encode(
                sys.getfilesystemencoding() or 'utf-8')
        assert not filename_template.endswith(_fs_transaction_suffix), \
            'filename templates may not end with %s' % _fs_transaction_suffix
        self.filename_template = filename_template
        self.renew_missing = renew_missing
        self.mode = mode 
Example 44
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: sessions.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, path=None, filename_template='werkzeug_%s.sess',
                 session_class=None, renew_missing=False, mode=0o644):
        SessionStore.__init__(self, session_class)
        if path is None:
            path = tempfile.gettempdir()
        self.path = path
        if isinstance(filename_template, text_type) and PY2:
            filename_template = filename_template.encode(
                sys.getfilesystemencoding() or 'utf-8')
        assert not filename_template.endswith(_fs_transaction_suffix), \
            'filename templates may not end with %s' % _fs_transaction_suffix
        self.filename_template = filename_template
        self.renew_missing = renew_missing
        self.mode = mode 
Example 45
Project: REMAKE   Author: PHIEZUKE   File: models.py    GNU General Public License v3.0 5 votes vote down vote up
def genTempFile(self, returnAs='path'):
        try:
            if returnAs not in ['file','path']:
                raise Exception('Invalid returnAs value')
            fName, fPath = 'linepy-%s-%i.bin' % (int(time.time()), randint(0, 9)), tempfile.gettempdir()
            if returnAs == 'file':
                return fName
            elif returnAs == 'path':
                return os.path.join(fPath, fName)
        except:
            raise Exception('tempfile is required') 
Example 46
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: bccache.py    MIT License 5 votes vote down vote up
def _get_default_cache_dir(self):
        def _unsafe_dir():
            raise RuntimeError('Cannot determine safe temp directory.  You '
                               'need to explicitly provide one.')

        tmpdir = tempfile.gettempdir()

        # On windows the temporary directory is used specific unless
        # explicitly forced otherwise.  We can just use that.
        if os.name == 'nt':
            return tmpdir
        if not hasattr(os, 'getuid'):
            _unsafe_dir()

        dirname = '_jinja2-cache-%d' % os.getuid()
        actual_dir = os.path.join(tmpdir, dirname)

        try:
            os.mkdir(actual_dir, stat.S_IRWXU)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
        try:
            os.chmod(actual_dir, stat.S_IRWXU)
            actual_dir_stat = os.lstat(actual_dir)
            if actual_dir_stat.st_uid != os.getuid() \
               or not stat.S_ISDIR(actual_dir_stat.st_mode) \
               or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
                _unsafe_dir()
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise

        actual_dir_stat = os.lstat(actual_dir)
        if actual_dir_stat.st_uid != os.getuid() \
           or not stat.S_ISDIR(actual_dir_stat.st_mode) \
           or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
            _unsafe_dir()

        return actual_dir 
Example 47
Project: flasky   Author: RoseOu   File: bccache.py    MIT License 5 votes vote down vote up
def __init__(self, directory=None, pattern='__jinja2_%s.cache'):
        if directory is None:
            directory = tempfile.gettempdir()
        self.directory = directory
        self.pattern = pattern 
Example 48
Project: flasky   Author: RoseOu   File: locations.py    MIT License 5 votes vote down vote up
def _get_build_prefix():
    """ Returns a safe build_prefix """
    path = os.path.join(tempfile.gettempdir(), 'pip_build_%s' %
        __get_username())
    if sys.platform == 'win32':
        """ on windows(tested on 7) temp dirs are isolated """
        return path
    try:
        os.mkdir(path)
        write_delete_marker_file(path)
    except OSError:
        file_uid = None
        try:
            # raises OSError for symlinks
            # https://github.com/pypa/pip/pull/935#discussion_r5307003
            file_uid = get_path_uid(path)
        except OSError:
            file_uid = None

        if file_uid != os.geteuid():
            msg = "The temporary folder for building (%s) is either not owned by you, or is a symlink." \
                % path
            print (msg)
            print("pip will not work until the temporary folder is " + \
                 "either deleted or is a real directory owned by your user account.")
            raise pip.exceptions.InstallationError(msg)
    return path 
Example 49
Project: flasky   Author: RoseOu   File: sessions.py    MIT License 5 votes vote down vote up
def __init__(self, path=None, filename_template='werkzeug_%s.sess',
                 session_class=None, renew_missing=False, mode=0o644):
        SessionStore.__init__(self, session_class)
        if path is None:
            path = tempfile.gettempdir()
        self.path = path
        if isinstance(filename_template, text_type) and PY2:
            filename_template = filename_template.encode(
                sys.getfilesystemencoding() or 'utf-8')
        assert not filename_template.endswith(_fs_transaction_suffix), \
            'filename templates may not end with %s' % _fs_transaction_suffix
        self.filename_template = filename_template
        self.renew_missing = renew_missing
        self.mode = mode 
Example 50
Project: CyberTK-Self   Author: CyberTKR   File: LineApi.py    GNU General Public License v2.0 5 votes vote down vote up
def sendVideoWithURL(self, to_, url):
        path = '%s/pythonLine-%i.data' % (tempfile.gettempdir(), randint(0, 9))

        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download video failure.')

        try:
            self.sendVideo(to_, path)
        except Exception as e:
            raise (e)