本文整理汇总了Python中shutil.move函数的典型用法代码示例。如果您正苦于以下问题:Python move函数的具体用法?Python move怎么用?Python move使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了move函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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
示例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)
示例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)
示例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
示例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 )
示例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
示例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]
示例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)
示例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()
示例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'))
示例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()
示例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")
示例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
示例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")