当前位置: 首页>>代码示例>>Python>>正文


Python tempfile.gettempdir函数代码示例

本文整理汇总了Python中tempfile.gettempdir函数的典型用法代码示例。如果您正苦于以下问题:Python gettempdir函数的具体用法?Python gettempdir怎么用?Python gettempdir使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了gettempdir函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_set_tmpdir

    def test_set_tmpdir(self):
        """Test set_tmpdir config function."""
        self.purge_environment()

        for tmpdir in [None, os.path.join(tempfile.gettempdir(), 'foo')]:
            parent = tmpdir
            if parent is None:
                parent = tempfile.gettempdir()

            mytmpdir = set_tmpdir(tmpdir=tmpdir)

            for var in ['TMPDIR', 'TEMP', 'TMP']:
                self.assertTrue(os.environ[var].startswith(os.path.join(parent, 'easybuild-')))
                self.assertEqual(os.environ[var], mytmpdir)
            self.assertTrue(tempfile.gettempdir().startswith(os.path.join(parent, 'easybuild-')))
            tempfile_tmpdir = tempfile.mkdtemp()
            self.assertTrue(tempfile_tmpdir.startswith(os.path.join(parent, 'easybuild-')))
            fd, tempfile_tmpfile = tempfile.mkstemp()
            self.assertTrue(tempfile_tmpfile.startswith(os.path.join(parent, 'easybuild-')))

            # cleanup
            os.close(fd)
            shutil.rmtree(mytmpdir)
            modify_env(os.environ, self.orig_environ)
            tempfile.tempdir = None
开发者ID:JensTimmerman,项目名称:easybuild-framework,代码行数:25,代码来源:config.py

示例2: train_from_file

    def train_from_file(self, conll_file, verbose=False):
        """
        Train MaltParser from a file
        
        :param conll_file: str for the filename of the training input data
        """
        if not self._malt_bin:
            raise Exception("MaltParser location is not configured.  Call config_malt() first.")

        # If conll_file is a ZipFilePathPointer, then we need to do some extra massaging
        f = None
        if hasattr(conll_file, 'zipfile'):
            zip_conll_file = conll_file
            conll_file = os.path.join(tempfile.gettempdir(),'malt_train.conll')
            conll_str = zip_conll_file.open().read()
            f = open(conll_file,'w')
            f.write(conll_str)
            f.close()        

        cmd = ['java', '-jar %s' % self._malt_bin, '-w %s' % tempfile.gettempdir(), 
               '-c %s' % self.mco, '-i %s' % conll_file, '-m learn']
        
#        p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
#                             stderr=subprocess.STDOUT,
#                             stdin=subprocess.PIPE)
#        (stdout, stderr) = p.communicate()
                
        self._execute(cmd, 'train', verbose)
        
        self._trained = True
开发者ID:approximatelylinear,项目名称:nltk,代码行数:30,代码来源:malt.py

示例3: test_tmp_dir_normal_1

    def test_tmp_dir_normal_1(self):
        tempdir = tempfile.gettempdir()
        # assert temp directory is empty
        self.assertListEqual(list(os.walk(tempdir)),
            [(tempdir, [], [])])

        witness = []

        @with_tempdir
        def createfile(list):
            fd1, fn1 = tempfile.mkstemp()
            fd2, fn2 = tempfile.mkstemp()
            dir = tempfile.mkdtemp()
            fd3, fn3 = tempfile.mkstemp(dir=dir)
            tempfile.mkdtemp()
            list.append(True)
            for fd in (fd1, fd2, fd3):
                os.close(fd)

        self.assertFalse(witness)
        createfile(witness)
        self.assertTrue(witness)

        self.assertEqual(tempfile.gettempdir(), tempdir)

        # assert temp directory is empty
        self.assertListEqual(list(os.walk(tempdir)),
            [(tempdir, [], [])])
开发者ID:Chaos99,项目名称:cachetools,代码行数:28,代码来源:unittest_testlib.py

示例4: __init__

  def __init__(self, host_name="localhost", port=None, user_name=None, password=None,
      db_name=None, log_sql=False):
    self._host_name = host_name
    self._port = port or self.PORT
    self._user_name = user_name or self.USER_NAME
    self._password = password or self.PASSWORD
    self.db_name = db_name
    self._conn = None
    self._connect()

    if log_sql:
      with DbConnection.LOCK:
        sql_log_path = gettempdir() + '/sql_log_%s_%s.sql' \
              % (self.db_type.lower(), time())
        self.sql_log = open(sql_log_path, 'w')
        link = gettempdir() + '/sql_log_%s.sql' % self.db_type.lower()
        try:
          unlink(link)
        except OSError as e:
          if 'No such file' not in str(e):
            raise e
        try:
          symlink(sql_log_path, link)
        except OSError as e:
          raise e
    else:
      self.sql_log = None
开发者ID:attilajeges,项目名称:incubator-impala,代码行数:27,代码来源:db_connection.py

示例5: processImage

 def processImage(self):
   """ starting with the original image, start processing each row """
   tier=(len(self._v_scaleInfo) -1)
   row = 0
   ul_y, lr_y = (0,0)
   root, ext = os.path.splitext(self._v_imageFilename)  
   if not root:
     root = self._v_imageFilename
   ext = '.jpg'
   while row * self.tileSize < self.originalHeight:
     ul_y = row * self.tileSize
     if (ul_y + self.tileSize) < self.originalHeight:
       lr_y = ul_y + self.tileSize
     else:
       lr_y = self.originalHeight
     image = self.openImage()
     imageRow = image.crop([0, ul_y, self.originalWidth, lr_y])
     saveFilename = root + str(tier) + '-' + str(row) +  ext
     if imageRow.mode != 'RGB':
       imageRow = imageRow.convert('RGB')
     imageRow.save(os.path.join(tempfile.gettempdir(), saveFilename), 'JPEG', quality=100)
     image = None
     imageRow = None
     if os.path.exists(os.path.join(tempfile.gettempdir(), saveFilename)): 
       self.processRowImage(tier=tier, row=row)
     row += 1
开发者ID:d-leroy,项目名称:ludecol,代码行数:26,代码来源:ZoomifyBase.py

示例6: main

def main():
  globs_to_delete = [
    # Clears run_isolated.zip.
    'run_isolated.zip',

    # Clears temporary directories generated by run_isolated.py.
    'run_tha_test*',
    'isolated_out*',

    # Clears temporary directories generated by Chromium tests.
    # TODO(maruel): This doesn't belong here, I wish these tests stopped
    # leaking.
    os.path.join(tempfile.gettempdir(), 'scoped_dir*'),
    os.path.join(tempfile.gettempdir(), 'zip_package*'),
  ]
  if sys.platform == 'win32':
    globs_to_delete.append(
        os.path.join(
            os.path.expanduser('~'), 'AppData', 'Roaming', 'Microsoft',
            'Windows', 'Recent', 'CustomDestinations', '*'))

  iterables = (glob.iglob(g) for g in globs_to_delete)
  for filename in itertools.chain.from_iterable(iterables):
    delete(filename)

  print ''
  return 0
开发者ID:bpsinc-native,项目名称:src_tools_swarming_client,代码行数:27,代码来源:swarm_cleanup.py

示例7: remove_graph_viz_temporaries

def remove_graph_viz_temporaries():
    """ remove_graph_viz_temporaries() -> None
    Removes temporary files generated by dot

    """
    os.unlink(tempfile.gettempdir() + "dot_output_vistrails.txt")
    os.unlink(tempfile.gettempdir() + "dot_tmp_vistrails.txt")
开发者ID:danielballan,项目名称:VisTrails,代码行数:7,代码来源:osx.py

示例8: _create_db_tables_and_add_users

def _create_db_tables_and_add_users():
    ctx.logger.info('Creating SQL tables and adding admin users...')
    create_script_path = 'components/restservice/config' \
                         '/create_tables_and_add_users.py'
    create_script_destination = join(tempfile.gettempdir(),
                                     'create_tables_and_add_users.py')
    ctx.download_resource(source=create_script_path,
                          destination=create_script_destination)
    # Directly calling with this python bin, in order to make sure it's run
    # in the correct venv
    python_path = '{0}/env/bin/python'.format(REST_SERVICE_HOME)
    runtime_props = ctx.instance.runtime_properties

    args_dict = json.loads(runtime_props['security_configuration'])
    args_dict['postgresql_host'] = runtime_props['postgresql_host']

    # The script won't have access to the ctx, so we dump the relevant args
    # to a JSON file, and pass its path to the script
    args_file_location = join(tempfile.gettempdir(), 'security_config.json')
    with open(args_file_location, 'w') as f:
        json.dump(args_dict, f)

    result = utils.sudo(
        [python_path, create_script_destination, args_file_location]
    )

    _log_results(result)
    utils.remove(args_file_location)
开发者ID:01000101,项目名称:cloudify-manager-blueprints,代码行数:28,代码来源:configure.py

示例9: testUnzipFileContainingLongPath

  def testUnzipFileContainingLongPath(self):
    try:
      dir_path = self.tmp_dir
      if sys.platform.startswith('win'):
        dir_path = u'\\\\?\\' + dir_path

      archive_suffix = ''
      # 260 is the Windows API path length limit.
      while len(archive_suffix) < 260:
        archive_suffix = os.path.join(archive_suffix, 'really')
      contents_dir_path = os.path.join(dir_path, archive_suffix)
      os.makedirs(contents_dir_path)
      filename = os.path.join(contents_dir_path, 'longpath.txt')
      open(filename, 'a').close()

      base_path = os.path.join(tempfile.gettempdir(), str(uuid.uuid4()))
      archive_path = shutil.make_archive(base_path, 'zip', dir_path)
      self.assertTrue(os.path.exists(archive_path))
      self.assertTrue(zipfile.is_zipfile(archive_path))
    except:
      if os.path.isfile(archive_path):
        os.remove(archive_path)
      raise

    unzip_path = os.path.join(tempfile.gettempdir(), str(uuid.uuid4()))
    dependency_manager_util.UnzipArchive(archive_path, unzip_path)
    dependency_manager_util.RemoveDir(unzip_path)
开发者ID:Hzj-jie,项目名称:android-sdk-linux,代码行数:27,代码来源:dependency_manager_util_unittest.py

示例10: main

def main():
	
	parser = argparse.ArgumentParser()
	parser.add_argument("--file", help="Target file for the compressed Build")
	parser.add_argument("--config", help="Select the configuration", default="Release")
	args = parser.parse_args()

	print(args.file)
	print(args.config)
	print(tempfile.gettempdir())

	prodbg_path = os.path.join(tempfile.gettempdir(), "prodbg")

	if (os.path.isdir(prodbg_path)):
		shutil.rmtree(prodbg_path)
	
	os.makedirs(prodbg_path)

	config_path = getConfigPath(args.config)

	# copy all the data to tempory directy

	copyDir(prodbg_path, os.path.join(config_path), ('*.pdb', '*.obj', '*.ilk', '*.lib', '*.exp', '*.exe')) 
	copyDir(prodbg_path, "temp", None) 
	copyDir(prodbg_path, "data", None) 
	copyFile(prodbg_path, os.path.join(config_path, "prodbg.exe"))

	# Compress to zip file

	zipBuild(args.file, prodbg_path)
开发者ID:HardlyHaki,项目名称:ProDBG,代码行数:30,代码来源:package_windows_build.py

示例11: unzip

def unzip(fhash,filename):
	(prefix, sep, suffix) = filename.rpartition('.')
	if remove_directory:
		prefix = directory+"/"+os.path.basename(prefix);
	found = 0;
	try:
		with zipfile.ZipFile(tempfile.gettempdir()+"/"+fhash+".zip") as zf:
			for member in zf.infolist():
				words = member.filename.split('/')
				path = "./"

				for word in words[:-1]:
					drive, word = os.path.splitdrive(word);
					head, word = os.path.split(word);
					if word in (os.curdir, os.pardir, ''): continue
					path = os.path.join(path, word);

				if re.match(r".*[.](srt|sub|ass)$",words[0].lower()) != None:
					zf.extract(member, tempfile.gettempdir()+"/");
					shutil.move(tempfile.gettempdir()+"/"+words[0], prefix+"."+(re.findall(r".*[.](srt|sub|ass)$",words[0].lower())[0]));
					if removeAd:
						adBlock(prefix+"."+(re.findall(r".*[.](srt|sub|ass)$",words[0].lower())[0]));
					found += 1;

	except zipfile.BadZipfile:
		os.unlink(tempfile.gettempdir()+"/"+fhash+".zip");
		raise Exception("Can't extract subtitles from downloaded file.")

	if found == 0:
		os.unlink(tempfile.gettempdir()+"/"+fhash+".zip");
		raise Exception("Subtitle file not found in archive.")
开发者ID:nechutny,项目名称:subs,代码行数:31,代码来源:subs.py

示例12: setUp

    def setUp(self):

        def createlayer(driver):
            lyr = shp.CreateLayer("edges", None, ogr.wkbLineString)
            namedef = ogr.FieldDefn("Name", ogr.OFTString)
            namedef.SetWidth(32)
            lyr.CreateField(namedef)
            return lyr

        drv = ogr.GetDriverByName("ESRI Shapefile")

        testdir = os.path.join(tempfile.gettempdir(),'shpdir')
        shppath = os.path.join(tempfile.gettempdir(),'tmpshp.shp')

        self.deletetmp(drv, testdir, shppath)
        os.mkdir(testdir)

        shp = drv.CreateDataSource(shppath)
        lyr = createlayer(shp)
        self.names = ['a','b','c']  #edgenames
        self.paths = (  [(1.0, 1.0), (2.0, 2.0)],
                        [(2.0, 2.0), (3.0, 3.0)],
                        [(0.9, 0.9), (4.0, 2.0)]
                    )
        for path,name in zip(self.paths, self.names):
            feat = ogr.Feature(lyr.GetLayerDefn())
            g = ogr.Geometry(ogr.wkbLineString)
            map(lambda xy: g.AddPoint_2D(*xy), path)
            feat.SetGeometry(g)
            feat.SetField("Name", name)
            lyr.CreateFeature(feat)
        self.shppath = shppath
        self.testdir = testdir
        self.drv = drv
开发者ID:aaronmcdaid,项目名称:networkx,代码行数:34,代码来源:test_shp.py

示例13: pre_start_restore

def pre_start_restore():
  """
  Restores the flume config, config dir, file/spillable channels to their proper locations
  after an upgrade has completed.
  :return:
  """
  Logger.info('Restoring Flume data and configuration after upgrade...')
  directoryMappings = _get_directory_mappings()

  for directory in directoryMappings:
    archive = os.path.join(tempfile.gettempdir(), BACKUP_TEMP_DIR,
      directoryMappings[directory])

    if os.path.isfile(archive):
      Logger.info('Extracting {0} to {1}'.format(archive, directory))
      tarball = None
      try:
        tarball = tarfile.open(archive, "r")
        tarball.extractall(directory)
      finally:
        if tarball:
          tarball.close()

    # cleanup
    if os.path.exists(os.path.join(tempfile.gettempdir(), BACKUP_TEMP_DIR)):
      shutil.rmtree(os.path.join(tempfile.gettempdir(), BACKUP_TEMP_DIR))
开发者ID:fanzhidongyzby,项目名称:ambari,代码行数:26,代码来源:flume_upgrade.py

示例14: trim_any_leftovers

def trim_any_leftovers():
    print tempfile.gettempdir()
    leftovers = glob.glob(os.path.join(tempfile.gettempdir(), 'mcworld_*', ''))
    for d in leftovers:
        print "Found left over directory: {}".format(d)
        if DO_REMOVE:
            shutil.rmtree(d, ignore_errors=True)
开发者ID:Iciciliser,项目名称:MCEdit-Unified,代码行数:7,代码来源:mcworld_support.py

示例15: processImage

 def processImage(self):
     """ starting with the original image, start processing each row """
     tier = len(self._v_scaleInfo) - 1
     row = 0
     ul_y, lr_y = (0, 0)
     root, ext = os.path.splitext(self._v_imageFilename)
     if not root:
         root = self._v_imageFilename
     ext = ".jpg"
     image = self.openImage()
     while row * self.tileSize < self.originalHeight:
         ul_y = row * self.tileSize
         if (ul_y + self.tileSize) < self.originalHeight:
             lr_y = ul_y + self.tileSize
         else:
             lr_y = self.originalHeight
         print "Going to open image"
         imageRow = image.crop([0, ul_y, self.originalWidth, lr_y])
         saveFilename = root + str(tier) + "-" + str(row) + ext
         if imageRow.mode != "RGB":
             imageRow = imageRow.convert("RGB")
         imageRow.save(os.path.join(tempfile.gettempdir(), saveFilename), "JPEG", quality=100)
         print "os path exist : %r" % os.path.exists(os.path.join(tempfile.gettempdir(), saveFilename))
         if os.path.exists(os.path.join(tempfile.gettempdir(), saveFilename)):
             self.processRowImage(tier=tier, row=row)
         row += 1
开发者ID:jerome-nexedi,项目名称:erp5,代码行数:26,代码来源:ERP5ZoomifyImage.py


注:本文中的tempfile.gettempdir函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。