本文整理汇总了Python中shutil.move函数的典型用法代码示例。如果您正苦于以下问题:Python move函数的具体用法?Python move怎么用?Python move使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了move函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: generateLocalConfig
def generateLocalConfig(localFile, build):
"""
Create resources/conf/localconfig.json and set the build values
appropriately.
"""
tmpOut = localFile + ".out"
with open(tmpOut, 'w') as f:
if os.path.exists(localFile):
data = json.load(open(localFile))
else:
data = {}
if build == 'debug-android' or build == 'debug-ios' or build == 'billingtest-android':
data['release'] = "debug"
elif build == 'ads-android' or build == 'ads-ios':
data['release'] = "ads"
elif build == 'paid-android' or build == 'paid-ios':
data['release'] = "paid"
elif build == 'samsung-android':
data['release'] = "samsung"
else:
assert 0, "run with build=something"
# force off the debug flag while building.
if data['release'] in ['paid', 'ads']:
data['debug'] = False
json.dump(data, f, indent=4)
shutil.move(tmpOut, localFile)
开发者ID:PossibleWhale,项目名称:Sheared,代码行数:30,代码来源:gcbuild.py
示例2: __remove_hotkey
def __remove_hotkey(self, command):
""" Remove the hotkey for 'command' (and 'command' too, of course). """
""" Return 'True' on success, 'False' otherwise. """
self.__touch_config_file()
oldfile = open(XBINDKEYS_CONFIG_FILE, "r")
newfile = open(XBINDKEYS_CONFIG_FILE + ".new", "w")
commandfound = False
skipnextline = False
for line in oldfile:
if skipnextline != True:
if line != '"' + command + '"\n':
newfile.write(line)
else:
commandfound = True
skipnextline = True
else:
skipnextline = False
oldfile.close()
newfile.close()
if commandfound == True:
try:
os.remove(XBINDKEYS_CONFIG_FILE)
except:
sessionlog.write("ERROR: 'Hotkeys.__remove_hotkey()' - Cannot replace '" + XBINDKEYS_CONFIG_FILE + "'.")
os.remove(XBINDKEYS_CONFIG_FILE + ".new")
return False
shutil.move(XBINDKEYS_CONFIG_FILE + ".new", XBINDKEYS_CONFIG_FILE)
else:
os.remove(XBINDKEYS_CONFIG_FILE + ".new")
return True
开发者ID:paucoma,项目名称:samsung-tools,代码行数:30,代码来源:hotkeys.py
示例3: extract_zip
def extract_zip(self, filename):
with zipfile.ZipFile(filename) as f:
# extractall doesn't work if zipfiles do not include directories
# as separate members (as for github and bitbucket)
topdirs = []
for m in f.namelist():
if m.endswith("/"):
if len(m.split("/")) == 2:
topdirs.append(m.split("/")[0])
continue
directory = "/".join(m.split("/")[0:-2])
if directory.find("/") == -1:
topdirs.append(directory)
if (len(directory) > 0 and
not directory.startswith("/") and
(directory.find("..") == -1) and
not os.path.exists(directory)):
os.makedirs(directory)
sys.stdout.write(".")
f.extract(m)
topdirs = filter(lambda x: len(x) != 0, topdirs)
topdirs = list(set(topdirs))
if not topdirs:
topdirs = [f.namelist()[0]]
if len(topdirs) > 1:
os.makedirs(self.path)
for d in topdirs:
shutil.move(d, "%s/%s" % (self.path, d))
else:
shutil.move(topdirs[0], self.path)
开发者ID:HPI-SWA-Lab,项目名称:RSqueak,代码行数:30,代码来源:download_dependencies.py
示例4: configure_linter
def configure_linter(self, language):
"""Fill out the template and move the linter into Packages."""
try:
if language is None:
return
if not self.fill_template(self.temp_dir, self.name, self.fullname, language):
return
git = util.which('git')
if git:
subprocess.call((git, 'init', self.temp_dest))
shutil.move(self.temp_dest, self.dest)
util.open_directory(self.dest)
self.wait_for_open(self.dest)
except Exception as ex:
sublime.error_message('An error occurred while configuring the plugin: {}'.format(str(ex)))
finally:
if self.temp_dir and os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir)
开发者ID:1901,项目名称:sublime_sync,代码行数:26,代码来源:commands.py
示例5: _stage_final_image
def _stage_final_image(self):
try:
fs_related.makedirs(self.__ensure_isodir() + "/LiveOS")
minimal_size = self._resparse()
if not self.skip_minimize:
fs_related.create_image_minimizer(self.__isodir + \
"/LiveOS/osmin.img",
self._image,
minimal_size)
if self.skip_compression:
shutil.move(self._image, self.__isodir + "/LiveOS/ext3fs.img")
else:
fs_related.makedirs(os.path.join(
os.path.dirname(self._image),
"LiveOS"))
shutil.move(self._image,
os.path.join(os.path.dirname(self._image),
"LiveOS", "ext3fs.img"))
fs_related.mksquashfs(os.path.dirname(self._image),
self.__isodir + "/LiveOS/squashfs.img")
self.__create_iso(self.__isodir)
if self.pack_to:
isoimg = os.path.join(self._outdir, self.name + ".iso")
packimg = os.path.join(self._outdir, self.pack_to)
misc.packing(packimg, isoimg)
os.unlink(isoimg)
finally:
shutil.rmtree(self.__isodir, ignore_errors = True)
self.__isodir = None
开发者ID:nataliakoval,项目名称:mic,代码行数:35,代码来源:livecd.py
示例6: filter_and_persist_proprietary_tool_panel_configs
def filter_and_persist_proprietary_tool_panel_configs( self, tool_configs_to_filter ):
"""Eliminate all entries in all non-shed-related tool panel configs for all tool config file names in the received tool_configs_to_filter."""
for proprietary_tool_conf in self.proprietary_tool_confs:
persist_required = False
tree, error_message = xml_util.parse_xml( proprietary_tool_conf )
if tree:
root = tree.getroot()
for elem in root:
if elem.tag == 'tool':
# Tools outside of sections.
file_path = elem.get( 'file', None )
if file_path:
if file_path in tool_configs_to_filter:
root.remove( elem )
persist_required = True
elif elem.tag == 'section':
# Tools contained in a section.
for section_elem in elem:
if section_elem.tag == 'tool':
file_path = section_elem.get( 'file', None )
if file_path:
if file_path in tool_configs_to_filter:
elem.remove( section_elem )
persist_required = True
if persist_required:
fh = tempfile.NamedTemporaryFile( 'wb', prefix="tmp-toolshed-fapptpc" )
tmp_filename = fh.name
fh.close()
fh = open( tmp_filename, 'wb' )
tree.write( tmp_filename, encoding='utf-8', xml_declaration=True )
fh.close()
shutil.move( tmp_filename, os.path.abspath( proprietary_tool_conf ) )
os.chmod( proprietary_tool_conf, 0644 )
开发者ID:HullUni-bioinformatics,项目名称:ReproPhyloGalaxy,代码行数:33,代码来源:tool_migration_manager.py
示例7: _put_filename
def _put_filename(self, key, filename):
target = self._build_filename(key)
shutil.move(filename, target)
# we do not know the permissions of the source file, rectify
self._fix_permissions(target)
return key
开发者ID:Chitrank-Dixit,项目名称:InMyMind,代码行数:7,代码来源:fs.py
示例8: main
def main(max_stations=0, folder='.'):
try:
makedirs(output_folder+'/'+folder)
except OSError:
pass
all_files = [ f for f in listdir(data_folder) if isfile(join(data_folder,f)) and f.endswith('.gz') ]
for ndf in all_files:
string = '_%dstations' % max_stations
new_name=ndf[:-7]+string+ndf[-7:]
rename(data_folder+'/'+ndf, data_folder+'/'+new_name)
all_files = [ f for f in listdir(data_folder) if isfile(join(data_folder,f)) and f.endswith('.gz') ]
for a_f in all_files:
move(data_folder+'/'+a_f, output_folder+'/'+folder+'/'+a_f)
print "Moved:", a_f[0:-3]
data_files = [ f for f in listdir(output_folder+'/'+folder) if isfile(join(output_folder+'/'+folder,f)) and f.endswith('.dat.gz') ]
print "\n"
for d_f in data_files:
fin = gzip.open(output_folder+'/'+folder+'/'+d_f, 'rb')
data = fin.read()
fin.close()
with open(output_folder+'/'+folder+'/'+d_f[0:-3],'w') as fout:
fout.write(data)
print "Unzipped:", d_f[0:-3]
开发者ID:EdwardBetts,项目名称:iclrt_tools,代码行数:32,代码来源:move_data.py
示例9: make_target_directory
def make_target_directory(self, path):
path = os.path.abspath(path)
try:
os.makedirs(path)
except OSError as e:
self.abort('Could not create target folder: %s' % e)
if os.path.isdir(path):
try:
if len(os.listdir(path)) != 0:
raise OSError('Directory not empty')
except OSError as e:
self.abort('Bad target folder: %s' % e)
scratch = os.path.join(tempfile.gettempdir(), uuid.uuid4().hex)
os.makedirs(scratch)
try:
yield scratch
except:
shutil.rmtree(scratch)
raise
else:
# Use shutil.move here in case we move across a file system
# boundary.
for filename in os.listdir(scratch):
if isinstance(path, unicode):
filename = filename.decode(fs_enc)
shutil.move(os.path.join(scratch, filename),
os.path.join(path, filename))
os.rmdir(scratch)
开发者ID:bestwpw,项目名称:lektor,代码行数:30,代码来源:quickstart.py
示例10: initialize
def initialize(self, test, log):
'''Does the init part of the test
1.Finds initial count of entry in log
2.Creates a file 'cron' under cron.d
3.Backs up /etc/crontab
4.Modifies /etc/crontab '''
self.log = log
self.initial_count = self.count_log('Cron automation')
f = open('/etc/cron.d/cron', 'w')
f.write('''#!/bin/bash
touch %s
echo 'Cron automation' >> %s
''' % (self.log, self.log))
f.close()
utils.system('chmod +x /etc/cron.d/cron')
shutil.copyfile('/etc/crontab', '/tmp/backup')
f = open('/etc/crontab', 'w')
f.write('* * * * * root run-parts /etc/cron.d/\n')
f.close()
if test == 'deny_cron':
if os.path.exists('/etc/cron.d/jobs.deny'):
shutil.move('/etc/cron.d/jobs.deny', '/tmp/jobs.deny')
f = open('/etc/cron.d/jobs.deny', 'w')
f.write('cron')
f.close()
elif test == 'allow_cron' :
os.remove('/etc/cron.d/jobs.deny')
if os.path.exists('/etc/cron.d/jobs.allow'):
shutil.move('/etc/cron.d/jobs.allow', '/tmp/jobs.allow')
f = open('/etc/cron.d/jobs.allow', 'w')
f.write('cron')
f.close()
开发者ID:dev-priya,项目名称:autotest-client-tests,代码行数:33,代码来源:crontab.py
示例11: deploy_wnmp
def deploy_wnmp():
os.chdir(os.path.join(BASE_DIR, 'wnmp'))
git_export('wnmp', TARGET_DIR)
# PHP
wget('http://windows.php.net/downloads/releases/'
'php-5.4.5-Win32-VC9-x86.zip',
sha1='028eb12e09fe011e20097c82064d6c550bf896c4')
logging.info('Extracting PHP...')
path = os.path.join(BASE_DIR, '_tmp', 'php')
makedirs(path, exist_ok=True)
ar = zipfile.ZipFile(
os.path.join(BASE_DIR, 'php-5.4.5-Win32-VC9-x86.zip'))
ar.extractall(path)
shutil.rmtree(os.path.join(TARGET_DIR, 'php'))
shutil.copytree(path, os.path.join(TARGET_DIR, 'php'))
# nginx
wget('http://nginx.org/download/nginx-1.2.2.zip',
sha1='0a5dfbb766bfefa238207db25d7b64b69aa37908')
logging.info('Extracting nginx...')
path = os.path.join(BASE_DIR, '_tmp')
makedirs(path, exist_ok=True)
ar = zipfile.ZipFile(
os.path.join(BASE_DIR, 'nginx-1.2.2.zip'))
ar.extractall(path)
shutil.rmtree(os.path.join(TARGET_DIR, 'nginx'))
shutil.copytree(os.path.join(path, 'nginx-1.2.2'),
os.path.join(TARGET_DIR, 'nginx'))
shutil.move(os.path.join(TARGET_DIR, 'example.nginx.conf'),
os.path.join(TARGET_DIR, 'nginx', 'conf', 'nginx.conf'))
# cleanup
shutil.rmtree(os.path.join(BASE_DIR, '_tmp'))
开发者ID:euphoris,项目名称:another-springnote,代码行数:34,代码来源:make.py
示例12: forwards
def forwards(self, orm):
"Write your forwards migration here"
for item in orm.AlbumConvertableItem.objects.all():
try:
image_path = item.image.image.path
except:
image_path = os.path.join(settings.MEDIA_ROOT, item.thumbFilename)
try:
os.stat(image_path)
except OSError as e:
if e.errno != 2:
raise e
else:
continue
old_dir, filename = os.path.split(image_path)
new_path = os.path.join('albums', str(item.parent.pk), str(item.pk))
new_dir = os.path.join(settings.MEDIA_ROOT, new_path)
try:
os.makedirs(new_dir)
except OSError as e:
if(e.errno != 17):
raise e
print "Directory %s already exists" % new_dir
print "Moving %s" % image_path
if(image_path != os.path.join(new_dir, filename)):
shutil.move(image_path, new_dir)
else:
print "Skipping"
item.preview = os.path.join(new_path, filename)
item.save()
开发者ID:jgroszko,项目名称:django-albums,代码行数:35,代码来源:0016_migrate_preview_data.py
示例13: docss
def docss():
""" Compresses the CSS files """
listCSS = []
f = open("sahana.css.cfg", "r")
files = f.readlines()
f.close()
for file in files[:-1]:
p = re.compile("(\n|\r|\t|\f|\v)+")
file = p.sub("", file)
listCSS.append("../../styles/%s" % file)
outputFilenameCSS = "sahana.min.css"
# Merge CSS files
print "Merging Core styles."
mergedCSS = mergeCSS(listCSS, outputFilenameCSS)
# Compress CSS files
print "Writing to %s." % outputFilenameCSS
compressCSS(mergedCSS, outputFilenameCSS)
# Move files to correct locations
print "Deleting %s." % outputFilenameCSS
try:
os.remove("../../styles/S3/%s" % outputFilenameCSS)
except:
pass
print "Moving new %s." % outputFilenameCSS
shutil.move(outputFilenameCSS, "../../styles/S3")
开发者ID:flavour,项目名称:lacity,代码行数:30,代码来源:build.sahana.py
示例14: hadoop_jar
def hadoop_jar(stdout, stderr, environ, *args):
if len(args) < 1:
stderr.write('RunJar jarFile [mainClass] args...\n')
return -1
jar_path = args[0]
if not os.path.exists(jar_path):
stderr.write(
'Exception in thread "main" java.io.IOException: Error opening job'
' jar: %s\n' % jar_path)
return -1
# only simulate for streaming steps
if HADOOP_STREAMING_JAR_RE.match(os.path.basename(jar_path)):
streaming_args = args[1:]
output_idx = list(streaming_args).index('-output')
assert output_idx != -1
output_dir = streaming_args[output_idx + 1]
real_output_dir = hdfs_path_to_real_path(output_dir, environ)
mock_output_dir = get_mock_hadoop_output()
if mock_output_dir is None:
stderr.write('Job failed!')
return -1
if os.path.isdir(real_output_dir):
os.rmdir(real_output_dir)
shutil.move(mock_output_dir, real_output_dir)
now = datetime.datetime.now()
stderr.write(now.strftime('Running job: job_%Y%m%d%H%M_0001\n'))
stderr.write('Job succeeded!\n')
return 0
开发者ID:ENuge,项目名称:mrjob,代码行数:34,代码来源:mockhadoop.py
示例15: cleanup
def cleanup(self, action):
if not self.steps_filename:
return
if not self.question_yes_no("All unused PPM files will be moved to a"
" backup directory. Are you sure?",
"Clean up data directory?"):
return
# Remember the current step index
current_step_index = self.current_step_index
# Get the backup dir
backup_dir = os.path.join(self.steps_data_dir, "backup")
# Create it if it doesn't exist
if not os.path.exists(backup_dir):
os.makedirs(backup_dir)
# Move all files to the backup dir
for filename in glob.glob(os.path.join(self.steps_data_dir,
"*.[Pp][Pp][Mm]")):
shutil.move(filename, backup_dir)
# Get the used files back
for step in self.steps:
self.set_state_from_step_lines(step, backup_dir, warn=False)
self.get_step_lines(self.steps_data_dir)
# Remove the used files from the backup dir
used_files = os.listdir(self.steps_data_dir)
for filename in os.listdir(backup_dir):
if filename in used_files:
os.unlink(os.path.join(backup_dir, filename))
# Restore step index
self.set_step(current_step_index)
# Inform the user
self.message("All unused PPM files may be found at %s." %
os.path.abspath(backup_dir),
"Clean up data directory")
开发者ID:Andrei-Stepanov,项目名称:virt-test,代码行数:33,代码来源:step_editor.py
示例16: env_teardown
def env_teardown():
'''
Teardown the testing environment.
'''
print('\n-----DESTROY ENV')
if len(PATHS) == 1:
print('Env setup not completed, check network connection.')
return
src_log = [path for path in PATHS if '.log' in path][-1]
dst_log = os.path.join('/tmp', 'test.log')
try:
delete_it(dst_log)
shutil.move(src_log, dst_log)
except IOError:
pass
env_status()
for path in PATHS:
delete_it(path)
env_config_teardown()
print('\n-----DESTROY ENV FINISHED')
开发者ID:starcraftman,项目名称:pakit,代码行数:25,代码来源:common.py
示例17: load
def load(self, fmu_path, output_dir):
"""Load the FMU for continued simulation in :meth:`continue_run`.
"""
import pyfmi
if 'log_level' in self._options:
self.fmu = pyfmi.load_fmu(fmu_path, log_level=self.log_level)
else:
self.fmu = pyfmi.load_fmu(fmu_path)
# Initialize the fmu, only call setup_experiment for FMUs 2.0
try:
self.fmu.setup_experiment()
version = 2
except AttributeError:
version = 1
self.fmu.initialize()
# Copy the log file to the result directory
log = ''
if version == 1:
log = self.fmu.get_identifier()
if version == 2:
log = self.fmu.get_name()
log += '_log.txt'
source = os.path.join(os.getcwd(), log)
destination = os.path.join(output_dir, 'log%i.txt' % self.interval)
move(source, destination)
开发者ID:kdavies4,项目名称:ModelicaRes,代码行数:30,代码来源:simulators.py
示例18: gen_moc
def gen_moc():
workDir = os.getcwd() + "/Gui"
print workDir
dirList = os.listdir(workDir)
for files in dirList:
if files.endswith(".h"):
print files
outp = "moc_" + files[:-2] + ".cpp"
print outp
affected = "./Gui/" + files
call(["moc", affected, "-o", outp])
#os.rename(outp, "./Gui/" + outp)
l = -1
f = open(outp)
lines = f.readlines()
f.close()
for line in lines:
if line[0] == '#':
break;
l = l + 1
if l >= 0:
f = open(outp, 'w');
lines[l] = '\n#include "EdPrec.h"\n'
f.writelines(lines)
f.close()
shutil.move(outp, "./Gui/" + outp)
开发者ID:yevgeniy-logachev,项目名称:framework2d,代码行数:29,代码来源:generate_moc.py
示例19: _initialize_metadata
def _initialize_metadata(self):
self._logger.info("Initializing the file metadata for {}...".format(self.basefolder))
old_metadata_path = os.path.join(self.basefolder, "metadata.yaml")
backup_path = os.path.join(self.basefolder, "metadata.yaml.backup")
if os.path.exists(old_metadata_path):
# load the old metadata file
try:
with open(old_metadata_path) as f:
import yaml
self._old_metadata = yaml.safe_load(f)
except:
self._logger.exception("Error while loading old metadata file")
# make sure the metadata is initialized as far as possible
self._list_folder(self.basefolder)
# rename the old metadata file
self._old_metadata = None
try:
import shutil
shutil.move(old_metadata_path, backup_path)
except:
self._logger.exception("Could not rename old metadata.yaml file")
else:
# make sure the metadata is initialized as far as possible
self._list_folder(self.basefolder)
self._logger.info("... file metadata for {} initialized successfully.".format(self.basefolder))
开发者ID:leductan-nguyen,项目名称:RaionPi,代码行数:31,代码来源:storage.py
示例20: moveOutput_VRay
def moveOutput_VRay(arg,frameNr, verbose):
if ((not arg.ElementsFolder) or (not arg.vraySeperateRenderChannels)):
return
import shutil
VRayExt=arg.FExt
if (arg.vraySeperateRenderChannels):
VRayExt=os.path.splitext(MaxPlus.Core.EvalMAXScript("renderers.production.output_splitfilename").Get())[1]
if (len(VRayExt)==0):
VRayExt=arg.FExt
FNameVar_Rendered= arg.FNameVar;
FNameVar_Rendered= FNameVar_Rendered.replace("<Channel>\\","")
if (argValid(arg.FNameVar) and MaxPlus.Core.EvalMAXScript("(maxOps.GetCurRenderElementMgr()).GetElementsActive()").Get()):
nrOfElements=MaxPlus.Core.EvalMAXScript("(maxOps.GetCurRenderElementMgr()).NumRenderElements()").Get()
for elemNr in xrange(0,nrOfElements):
elemName=MaxPlus.Core.EvalMAXScript("((maxOps.GetCurRenderElementMgr()).GetRenderElement "+str(elemNr)+").elementName").Get()
elemName=elemName.replace(" ","_")
fileout_Rendered=FNameVar_Rendered+str(frameNr).zfill(int(arg.FPadding))+VRayExt
fileout_Should =arg.FNameVar +str(frameNr).zfill(int(arg.FPadding))+VRayExt
fileout_Rendered=fileout_Rendered.replace("<Channel>",elemName)
fileout_Should =fileout_Should .replace("<Channel>",elemName)
if (not os.path.isfile(fileout_Rendered)):
logMessageGen("WRN", "Element file to be moved to subfolder not found: "+fileout_Rendered,1)
continue;
if (verbose):
logMessage("Moving element '"+fileout_Rendered+"' => '"+fileout_Should+"'")
shutil.move(fileout_Rendered,fileout_Should)
开发者ID:michimussato,项目名称:pypelyne2,代码行数:27,代码来源:kso_3dsmax.py
注:本文中的shutil.move函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论