當前位置: 首頁>>代碼示例>>Python>>正文


Python shutil.move方法代碼示例

本文整理匯總了Python中shutil.move方法的典型用法代碼示例。如果您正苦於以下問題:Python shutil.move方法的具體用法?Python shutil.move怎麽用?Python shutil.move使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在shutil的用法示例。


在下文中一共展示了shutil.move方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: downloadDemo

# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import move [as 別名]
def downloadDemo(which):
    try:
        downloadDir = tempfile.mkdtemp()
        archivePath = "{}/svviz-data.zip".format(downloadDir)

        # logging.info("Downloading...")
        downloadWithProgress("http://svviz.github.io/svviz/assets/examples/{}.zip".format(which), archivePath)
        
        logging.info("Decompressing...")
        archive = zipfile.ZipFile(archivePath)
        archive.extractall("{}".format(downloadDir))

        if not os.path.exists("svviz-examples"):
            os.makedirs("svviz-examples/")

        shutil.move("{temp}/{which}".format(temp=downloadDir, which=which), "svviz-examples/")
    except Exception as e:
        print("error downloading and decompressing example data: {}".format(e))
        return False

    if not os.path.exists("svviz-examples"):
        print("error finding example data after download and decompression")
        return False
    return True 
開發者ID:svviz,項目名稱:svviz,代碼行數:26,代碼來源:demo.py

示例2: restore_config_file

# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import move [as 別名]
def restore_config_file():
    os.remove(zmirror_file('config.py'))
    os.remove(zmirror_file('custom_func.py'))
    if os.path.exists(zmirror_file('config.py._unittest_raw')):
        shutil.move(zmirror_file('config.py._unittest_raw'), zmirror_file('config.py'))
    if os.path.exists(zmirror_file('custom_func.py._unittest_raw')):
        shutil.move(zmirror_file('custom_func.py._unittest_raw'), zmirror_file('custom_func.py'))

    try:
        os.remove(zmirror_file('ip_whitelist.txt'))
    except:
        pass
    try:
        os.remove(zmirror_file('ip_whitelist.log'))
    except:
        pass
    try:
        os.remove(zmirror_file('automatic_domains_whitelist.log'))
    except:
        pass 
開發者ID:aploium,項目名稱:zmirror,代碼行數:22,代碼來源:utils.py

示例3: __init__

# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import move [as 別名]
def __init__(self, tarpath, basepath='', cache_path=None, tarball_name=None):
        OSPath.__init__(self, basepath, cache_path=cache_path)
        object.__setattr__(self, 'tarball_path', tarpath)
        object.__setattr__(self, 'base_path', basepath)
        if cache_path == tarpath:
            # we need to prep the path
            tarfl = os.path.split(tarpath)[1]
            cpath = os.path.join(cache_path, 'contents')
            tarpath = os.path.join(cache_path, tarfl)
            if os.path.isfile(cache_path):
                # we need to move things around
                td = tmpdir(delete=True)
                tmpfl = os.path.join(td,tarfl)
                shutil.move(cache_path, tmpfl)
                if not os.path.isdir(cpath): os.makedirs(cpath, mode=0o755)
                shutil.move(tmpfl, tarpath)
            object.__setattr__(self, 'tarball_path', tarpath)
            object.__setattr__(self, 'cache_path', cpath)
        # get the tarball 'name'
        flnm = os.path.split(self.tarball_path if tarball_name is None else tarball_name)[-1]
        tarball_name = flnm.split('.tar')[0]
        object.__setattr__(self, 'tarball_name', tarball_name) 
開發者ID:noahbenson,項目名稱:neuropythy,代碼行數:24,代碼來源:filemap.py

示例4: setup_logging

# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import move [as 別名]
def setup_logging(log_loc):
    if os.path.exists(log_loc):
        shutil.move(log_loc, log_loc + "_" + str(int(os.path.getctime(log_loc))))
    os.makedirs(log_loc)

    log_file = '{}/benchmark.log'.format(log_loc)
    LOGGER = logging.getLogger('benchmark')
    LOGGER.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s %(levelname)s:%(name)s %(message)s')
    file_handler = logging.FileHandler(log_file)
    console_handler = logging.StreamHandler()
    file_handler.setFormatter(formatter)
    console_handler.setFormatter(formatter)

    LOGGER.addHandler(file_handler)
    LOGGER.addHandler(console_handler)
    return LOGGER 
開發者ID:awslabs,項目名稱:dynamic-training-with-apache-mxnet-on-aws,代碼行數:19,代碼來源:benchmark.py

示例5: test_dyld_library_path_lookups

# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import move [as 別名]
def test_dyld_library_path_lookups():
    # Test that DYLD_LIBRARY_PATH can be used to find libs during
    # delocation
    with TempDirWithoutEnvVars('DYLD_LIBRARY_PATH') as tmpdir:
        # Copy libs into a temporary directory
        subtree = pjoin(tmpdir, 'subtree')
        all_local_libs = _make_libtree(subtree)
        liba, libb, libc, test_lib, slibc, stest_lib = all_local_libs
        # move libb and confirm that test_lib doesn't work
        hidden_dir = 'hidden'
        os.mkdir(hidden_dir)
        new_libb = os.path.join(hidden_dir, os.path.basename(LIBB))
        shutil.move(libb,
                    new_libb)
        assert_raises(RuntimeError, back_tick, [test_lib])
        # Update DYLD_LIBRARY_PATH and confirm that we can now
        # successfully delocate test_lib
        os.environ['DYLD_LIBRARY_PATH'] = hidden_dir
        delocate_path('subtree', 'deplibs')
        back_tick(test_lib) 
開發者ID:matthew-brett,項目名稱:delocate,代碼行數:22,代碼來源:test_delocating.py

示例6: get_return_label

# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import move [as 別名]
def get_return_label(self):
        """Get the GSX return label for this part."""
        if self.return_label.name == "":
            # Return label not yet set, get it...
            label = gsxws.Return(self.return_order).get_label(self.part_number)
            filename = "%s_%s.pdf" % (self.return_order, self.part_number)
            tmp_fp = os.path.join(settings.TEMP_ROOT, filename)
            #  move the label to local temp to avoid
            #  django.security.SuspiciousFileOperation
            shutil.move(label.returnLabelFileData, tmp_fp)

            f = File(open(tmp_fp, 'r'))
            self.return_label = f
            self.save()
            self.return_label.save(filename, f)
            f.closed
            os.remove(tmp_fp)

        return self.return_label.read() 
開發者ID:fpsw,項目名稱:Servo,代碼行數:21,代碼來源:parts.py

示例7: replace_old_db_with_new

# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import move [as 別名]
def replace_old_db_with_new(self):
        global con
        global DATABASE_PATH

        temp_db_path = TEMP_PATH + '/angry_database.db'

        dir_path = os.path.dirname(DATABASE_PATH)

        if not os.path.exists(temp_db_path):
            return
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)

        if con:
            con.close()
        shutil.move(temp_db_path, DATABASE_PATH)

        con = sqlite3.connect(DATABASE_PATH, check_same_thread=False)
        con.create_function("regexp", 2, regexp) 
開發者ID:DoTheEvo,項目名稱:ANGRYsearch,代碼行數:21,代碼來源:angrysearch.py

示例8: loadstate

# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import move [as 別名]
def loadstate():
    global STATE, STATEFILE
    if os.getenv("HOME") is not None:
        STATEFILE = os.path.join(os.getenv("HOME"), ".epr")
        if os.path.isdir(os.path.join(os.getenv("HOME"), ".config")):
            configdir = os.path.join(os.getenv("HOME"), ".config", "epr")
            os.makedirs(configdir, exist_ok=True)
            if os.path.isfile(STATEFILE):
                if os.path.isfile(os.path.join(configdir, "config")):
                    os.remove(os.path.join(configdir, "config"))
                shutil.move(STATEFILE, os.path.join(configdir, "config"))
            STATEFILE = os.path.join(configdir, "config")
    elif os.getenv("USERPROFILE") is not None:
        STATEFILE = os.path.join(os.getenv("USERPROFILE"), ".epr")
    else:
        STATEFILE = os.devnull

    if os.path.exists(STATEFILE):
        with open(STATEFILE, "r") as f:
            STATE = json.load(f) 
開發者ID:wustho,項目名稱:epr,代碼行數:22,代碼來源:epr.py

示例9: purge_checkpoints

# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import move [as 別名]
def purge_checkpoints(log_dir_root, target_dir, verbose):
    vprint = print if verbose else no_op.NoOp
    ckpt_dir_glob = Saver.ckpt_dir_for_log_dir(path.join(log_dir_root, '*'))
    ckpt_dir_matches = sorted(glob.glob(ckpt_dir_glob))
    for ckpt_dir in ckpt_dir_matches:
        log_dir = Saver.log_dir_from_ckpt_dir(ckpt_dir)
        all_ckpts = Saver.all_ckpts_with_iterations(ckpt_dir)
        if len(all_ckpts) <= 5:
            vprint('Skipping {}'.format(log_dir))
            continue
        target_log_dir = path.join(target_dir, path.basename(log_dir))
        target_ckpt_dir = Saver.ckpt_dir_for_log_dir(target_log_dir)
        os.makedirs(target_ckpt_dir, exist_ok=True)
        ckpts_to_keep = {all_ckpts[2], all_ckpts[len(all_ckpts) // 2], all_ckpts[-1]}
        ckpts_to_move = set(all_ckpts) - ckpts_to_keep
        vprint('Moving to {}:'.format(target_ckpt_dir))
        for _, ckpt_to_move in ckpts_to_move:
            # ckpt_to_move is /path/to/dir/ckpt-7000, add a * to match ckpt-7000.data, .meta, .index
            for ckpt_file in glob.glob(ckpt_to_move + '*'):
                vprint('- {}'.format(ckpt_file))
                shutil.move(ckpt_file, target_ckpt_dir) 
開發者ID:fab-jul,項目名稱:imgcomp-cvpr,代碼行數:23,代碼來源:purge_checkpoints.py

示例10: put

# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import move [as 別名]
def put(self, key, sync_object, callback=None):
        path = os.path.join(self.path, key)
        self.ensure_path(path)

        BUFFER_SIZE = 4096
        fd, temp_path = tempfile.mkstemp()

        try:
            with open(temp_path, "wb") as fp_1:
                while True:
                    data = sync_object.fp.read(BUFFER_SIZE)
                    fp_1.write(data)
                    if callback is not None:
                        callback(len(data))
                    if len(data) < BUFFER_SIZE:
                        break
            shutil.move(temp_path, path)
        except Exception:
            os.remove(temp_path)
            raise
        finally:
            os.close(fd)

        self.set_remote_timestamp(key, sync_object.timestamp) 
開發者ID:MichaelAquilina,項目名稱:S4,代碼行數:26,代碼來源:local.py

示例11: cache_or_load_file

# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import move [as 別名]
def cache_or_load_file(path, creator, loader):
    if os.path.exists(path):
        return loader(path)

    try:
        os.makedirs(_cache_root)
    except OSError:
        if not os.path.isdir(_cache_root):
            raise RuntimeError('cannot create cache directory')

    with tempdir() as temp_dir:
        filename = os.path.basename(path)
        temp_path = os.path.join(temp_dir, filename)
        content = creator(temp_path)
        if not os.path.exists(path):
            shutil.move(temp_path, path)

    return content 
開發者ID:tofunlp,項目名稱:lineflow,代碼行數:20,代碼來源:download.py

示例12: document

# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import move [as 別名]
def document():
    bootstrap()
    clean_up(('_build',
              os.path.join('docs', '_build'),
              os.path.join('docs', 'test_docs.rst'),
              os.path.join('docs', 'modules.rst')))
    success = execute_command('make -C docs html')
    if success:
        shutil.move(os.path.join('docs', '_build'), '_build')
        try:
            open_file(os.path.join('_build', 'html', 'index.html'))
        except Exception:
            LOGGER.warning('Could not execute UI portion. Maybe running headless?')
        LOGGER.info('%s Successfully built documentation %s',
                    emojize(':white_heavy_check_mark:'),
                    emojize(':thumbs_up:'))
    else:
        LOGGER.error('%s Documentation creation errors found! %s',
                     emojize(':cross_mark:'),
                     emojize(':crying_face:'))
    raise SystemExit(0 if success else 1) 
開發者ID:costastf,項目名稱:toonapilib,代碼行數:23,代碼來源:document.py

示例13: replace_gmsh

# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import move [as 別名]
def replace_gmsh():
    fn_gmsh = path2bin('gmsh')
    fn_gmsh_tmp = path2bin('gmsh_tmp')
    # move
    shutil.move(fn_gmsh, fn_gmsh_tmp)
    # replace
    if sys.platform == 'win32':
        fn_script = fn_gmsh[:4] + '.cmd'
        with open(fn_script, 'w') as f:
            f.write('echo "GMSH"')
    else:
        with open(fn_gmsh, 'w') as f:
            f.write('#! /bin/bash -e\n')
            f.write(f'"echo" "$@"')
        os.chmod(
            fn_gmsh,
            os.stat(fn_gmsh).st_mode |
            stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
        )
    yield
    shutil.move(fn_gmsh_tmp, fn_gmsh) 
開發者ID:simnibs,項目名稱:simnibs,代碼行數:23,代碼來源:examples.py

示例14: replace_show_surface

# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import move [as 別名]
def replace_show_surface():
    fn_orig = os.path.abspath(
        os.path.join(
            os.path.dirname(__file__),
            '..', '..', 'matlab',
            'mesh_show_surface.m'
        )
    )
    fn_tmp = fn_orig + '.bk'
    shutil.move(fn_orig, fn_tmp)
    # replace
    with open(fn_orig, 'w') as f:
        f.write('function varargout = mesh_show_surface(m, varargin)\n')
        f.write('end')
    yield
    shutil.move(fn_tmp, fn_orig) 
開發者ID:simnibs,項目名稱:simnibs,代碼行數:18,代碼來源:examples.py

示例15: download_extra_coils

# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import move [as 別名]
def download_extra_coils(timeout=None):
    version = 'master'
    url = f'https://github.com/simnibs/simnibs-coils/archive/{version}.zip'
    with tempfile.NamedTemporaryFile('wb', delete=False) as tmpf:
        tmpname = tmpf.name
    reporthook = functools.partial(_download_manager, start_time=time.time(), timeout=timeout)
    urllib.request.urlretrieve(url, tmpf.name, reporthook=reporthook)
    with zipfile.ZipFile(tmpname) as z:
        z.extractall(os.path.join(SIMNIBSDIR, 'ccd-files'))
    os.remove(tmpname)
    src = os.path.join(SIMNIBSDIR, 'ccd-files', f'simnibs-coils-{version}')
    dest = os.path.join(SIMNIBSDIR, 'ccd-files')
    for f in glob.glob(os.path.join(src, '*')):
        d = os.path.join(dest, os.path.basename(f))
        if os.path.isdir(d):
            shutil.rmtree(d)
        if os.path.isfile(d):
            os.remove(d)
        shutil.move(f, d)
    shutil.rmtree(
        os.path.join(SIMNIBSDIR, 'ccd-files', f'simnibs-coils-{version}')) 
開發者ID:simnibs,項目名稱:simnibs,代碼行數:23,代碼來源:postinstall_simnibs.py


注:本文中的shutil.move方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。