def remove(self, force=False): """ Removes the Container of Applications (dmgs, zips, pkgs). This method can only be called after install() has run succesfully. Args: force: If set, Installable will be removed even if it has not been installed. Defaults to 'False' Raises: NotInstalledException: If Installable().install has not been called successfully and force is 'False' """ if not self.installed and not force: logger.debug("Cant remove %s!" % self) raise NotInstalledException() try: send2trash.send2trash(self.path) self.removed = True logger.info("Moved %s to trash." % self) except OSError as ose: logger.exception(ose)
def execute_repair(self): repairedfiles=[] recreatedfiles=[] if self.len_verified_actions>0: for f,retcode in self.verifiedfiles_repairable: yield f retval = self.runpar([self.par_cmd,"r",f]) if retval == 0: if not self.keep_old and os.path.isfile(f+".1"): send2trash(f+".1") repairedfiles.append([ f , retval ]) for f,retcode in self.verifiedfiles_err: yield f pars = glob.glob(glob.escape(f)+'*.par2') for p in pars: send2trash(p) recreatedfiles.append([ f , self.runpar([self.par_cmd,"c","-r"+self.percentage,"-n"+self.nr_parfiles,f]) ]) self.recreate = sorted(recreatedfiles) self.recreate_err = sorted([f for f,err in recreatedfiles if err !=0]) self.fixes = sorted([f for f,err in repairedfiles if err ==0]) self.fixes_err = sorted([f for f,err in repairedfiles if err !=0]) self.len_all_err = self.len_all_err + len(self.recreate_err) + len(self.fixes_err) return
def deleteLocalFile(self, localPath, remotePath): #logging.warn('delete local file %s' % localPath) head, tail = os.path.split(localPath) self.outputQueue.put(messages.Status('Deleting %s' % tail)) send2trash(localPath) self.state.removeObjectSyncRecord(remotePath) self.outputQueue.put(self._get_working_message())
def run(self, dirs): if sublime.ok_cancel_dialog("Delete Folder?", "Delete"): try: for d in dirs: send2trash.send2trash(d) except: sublime.status_message("Unable to delete folder")
def import_file(_file, destination, album_from_folder, trash, allow_duplicates): """Set file metadata and move it to destination. """ if not os.path.exists(_file): log.warn('Could not find %s' % _file) print('{"source":"%s", "error_msg":"Could not find %s"}' % \ (_file, _file)) return # Check if the source, _file, is a child folder within destination elif destination.startswith(os.path.dirname(_file)): print('{"source": "%s", "destination": "%s", "error_msg": "Source cannot be in destination"}' % (_file, destination)) return media = Media.get_class_by_file(_file, [Text, Audio, Photo, Video]) if not media: log.warn('Not a supported file (%s)' % _file) print('{"source":"%s", "error_msg":"Not a supported file"}' % _file) return if album_from_folder: media.set_album_from_folder() dest_path = FILESYSTEM.process_file(_file, destination, media, allowDuplicate=allow_duplicates, move=False) if dest_path: print('%s -> %s' % (_file, dest_path)) if trash: send2trash(_file) return dest_path or None
def backup(self): nbacks = self.pm.profile['numBackups'] if not nbacks: return dir = self.pm.backupFolder() path = self.pm.collectionPath() # find existing backups backups = [] for file in os.listdir(dir): m = re.search("backup-(\d+).apkg", file) if not m: # unknown file continue backups.append((int(m.group(1)), file)) backups.sort() # get next num if not backups: n = 1 else: n = backups[-1][0] + 1 # do backup newpath = os.path.join(dir, "backup-%d.apkg" % n) z = zipfile.ZipFile(newpath, "w", zipfile.ZIP_DEFLATED) z.write(path, "collection.anki2") z.writestr("media", "{}") z.close() # remove if over if len(backups) + 1 > nbacks: delete = len(backups) + 1 - nbacks delete = backups[:delete] for file in delete: send2trash(os.path.join(dir, file[1]))
def remove(self, name): p = self.profileFolder() if os.path.exists(p): send2trash(p) self.db.execute("delete from profiles where name = ?", name.encode("utf8")) self.db.commit()
def check_recycle(name, verbose=True): """ places old file in recycle bin, if it exists. this should work for any system, but requires the send2trash module (see https://pypi.python.org/pypi/Send2Trash) input: name = file name, with extension (must be in current working dir) verbose = optional input (default=True) which will print messages to the command window """ # import send2trash module: # it's bad practice to import within a function, but the use of # check_recycle is optional, since check_delete exists. Thus, I don't # want the import of myFileOperations to break simply because someone # does not have the optional send2trash module installed... from send2trash import send2trash if verbose: try: send2trash(name) print "\nold file sent to recycle bin" print 'saving new "%s"\n' % (name) except: print '\nno file found, saving new file "%s"\n' % (name) else: try: send2trash(name) except: pass
def clean_empty_dirs(): #print 'cleaning dirs...' def get_subdirs(path): for root, dirs, files in os.walk(path): return [os.path.join(root, x) for x in dirs] return [] def has_subs(path): for root, dirs, files in os.walk(path): files = [x for x in files if not x.startswith('.')] return len(dirs)+len(files) != 0 return False for show_dir in get_subdirs(tv_shows_dir): for subdir in get_subdirs(show_dir): if not has_subs(subdir): #print 'removing directory',subdir if not DEBUG: send2trash(subdir) continue for subdir2 in get_subdirs(subdir): if not has_subs(subdir2): #print 'removing directory',subdir2 if not DEBUG: send2trash(subdir2)
def run(self, edit): f = self.view.file_name() if (f is None): return send2trash.send2trash(f) self.view.window().run_command('close')
def backup(self): nbacks = self.pm.profile['numBackups'] if not nbacks or devMode: return dir = self.pm.backupFolder() path = self.pm.collectionPath() # do backup fname = time.strftime("backup-%Y-%m-%d-%H.%M.%S.apkg", time.localtime(time.time())) newpath = os.path.join(dir, fname) data = open(path, "rb").read() b = self.BackupThread(newpath, data) b.start() # find existing backups backups = [] for file in os.listdir(dir): # only look for new-style format m = re.match("backup-\{4}-.+.apkg", file) if not m: continue backups.append(file) backups.sort() # remove old ones while len(backups) > nbacks: fname = backups.pop(0) path = os.path.join(dir, fname) send2trash(path)
def delete_file(self, path): """Delete file at path.""" path = path.strip('/') os_path = self._get_os_path(path) rm = os.unlink if os.path.isdir(os_path): listing = os.listdir(os_path) # Don't delete non-empty directories. # A directory containing only leftover checkpoints is # considered empty. cp_dir = getattr(self.checkpoints, 'checkpoint_dir', None) for entry in listing: if entry != cp_dir: raise web.HTTPError(400, u'Directory %s not empty' % os_path) elif not os.path.isfile(os_path): raise web.HTTPError(404, u'File does not exist: %s' % os_path) if self.delete_to_trash: self.log.debug("Sending %s to trash", os_path) # Looking at the code in send2trash, I don't think the errors it # raises let us distinguish permission errors from other errors in # code. So for now, just let them all get logged as server errors. send2trash(os_path) return if os.path.isdir(os_path): self.log.debug("Removing directory %s", os_path) with self.perm_to_403(): shutil.rmtree(os_path) else: self.log.debug("Unlinking file %s", os_path) with self.perm_to_403(): rm(os_path)
def extensionchange(): global numExfilFiles, numFiles, dT, eD,gpath currentFile=0 while currentFile<=numFiles: shutil.copy2(gpath+"\\"+str(currentFile)+"combinedExfil.txt", gpath+"\\X"+str(currentFile)+"combinedExfil.txt.wav")#There are modules for reading wav files, have not added wav exfil support if reading file is required send2trash(gpath+"\\"+str(currentFile)+"combinedExfil.txt") numExfilFiles=numFiles
def deleteFile(path): for foldername, subfolders, filenames in os.walk(path): for filename in filenames: filePath = os.path.join(foldername, filename) if os.path.getsize(filePath) > MaxSize: print(filename + " is more than 100MB") send2trash.send2trash(filePath)
def find_all(name, path): result = [] for root, dirs, files in os.walk(path): if name in files: result.append(os.path.join(root, name)) send2trash(os.path.join(root, name)) return len(result)
def delete(self, ref): os_path = self._abspath(ref) # Remove the \\?\ for SHFileOperation on win if os_path[:4] == '\\\\?\\': # http://msdn.microsoft.com/en-us/library/cc249520.aspx # SHFileOperation don't handle \\?\ paths if len(os_path) > 260: # Rename to the drive root info = self.move(ref, '/') new_ref = info.path try: send2trash(self._abspath(new_ref)[4:]) except: log.info('Cant use trash for ' + os_path + ', delete it') self.delete_final(new_ref) return else: os_path = os_path[4:] log.info('Send ' + os_path + ' to trash') try: send2trash(os_path) except: log.info('Cant use trash for ' + os_path + ', delete it') self.delete_final(ref)
def import_file(_file, destination, album_from_folder, trash): """Set file metadata and move it to destination. """ if not os.path.exists(_file): if constants.debug: print 'Could not find %s' % _file print '{"source":"%s", "error_msg":"Could not find %s"}' % \ (_file, _file) return media = Media.get_class_by_file(_file, [Audio, Photo, Video]) if not media: if constants.debug: print 'Not a supported file (%s)' % _file print '{"source":"%s", "error_msg":"Not a supported file"}' % _file return if media.__name__ == 'Video': FILESYSTEM.set_date_from_path_video(media) if album_from_folder: media.set_album_from_folder() dest_path = FILESYSTEM.process_file(_file, destination, media, allowDuplicate=False, move=False) if dest_path: print '%s -> %s' % (_file, dest_path) if trash: send2trash(_file)
def delete_path(path): "Deletes the provided recursively" s = True if os.path.exists(path): error = '' if app_constants.SEND_FILES_TO_TRASH: try: send2trash.send2trash(path) except: log.exception("Unable to send file to trash") error = 'Unable to send file to trash' else: try: if os.path.isfile(path): os.remove(path) else: shutil.rmtree(path) except PermissionError: error = 'PermissionError' except FileNotFoundError: pass if error: p = os.path.split(path)[1] log_e('Failed to delete: {}:{}'.format(error, p)) app_constants.NOTIF_BAR.add_text('An error occured while trying to delete: {}'.format(error)) s = False return s
def main(root_path): for root, dirs, files in os.walk(root_path): log_info('Processing Path ' + root) for file in files: process_file(root +'/' + file) if delete_invalid_archives and len(files_to_delete) > 0: sys.stdout.write('\n' + '*' * 80) sys.stdout.write('\n* WARNING THE FOLLOWING FILES WILL BE DELETED:') sys.stdout.write('\n' + '*' * 80) for file_name in files_to_delete: sys.stdout.write('\n* WARNING: Ready to DELETE'+ file_name) sys.stdout.write('\n' + '*' * 80) sys.stdout.write('\n') answer = query_yes_no('DELETE ALL ' + str(len(files_to_delete)) + ' (APPARENTLY) INVALID FILES?', default="no") if answer: try: import send2trash except ImportError: send2trash_available = False else: send2trash_available = True if send2trash_available and query_yes_no('Send to trash', default="yes"): for file_name in files_to_delete: log_info('Sending to Trash ' + file_name) send2trash.send2trash(file_name) else: for file_name in files_to_delete: log_info('DELETING! ' + file_name) os.remove(file_name) else: log_info('NO file deletion has occurred') sys.stdout.write("\nStephen's Archive Re-Touch Utility Complete\n")
def delete(self, ref): locker = self.unlock_ref(ref) os_path = self._abspath(ref) if not self.exists(ref): return # Remove the \\?\ for SHFileOperation on win if os_path[:4] == '\\\\?\\': # http://msdn.microsoft.com/en-us/library/cc249520.aspx # SHFileOperation don't handle \\?\ paths if len(os_path) > 260: # Rename to the drive root info = self.move(ref, '/') new_ref = info.path try: send2trash(self._abspath(new_ref)[4:]) except: log.debug('Cant use trash for ' + os_path + ', delete it') self.delete_final(new_ref) return else: os_path = os_path[4:] log.trace('Send ' + os_path + ' to trash') try: send2trash(os_path) except: log.debug('Cant use trash for ' + os_path + ', delete it') self.delete_final(ref) finally: # Dont want to unlock the current deleted self.lock_ref(ref, locker & 2)
def run(self, paths = [], confirmed = 'False'): print '--------------' print 'deleting paths' print paths print 'confirmed' print confirmed if confirmed == 'False' and s.get('confirm_before_deleting', True): print 'confirmed == False and confirm_before_deleting == True' self.confirm([item.path() for item in SideBarSelection(paths).getSelectedItems()], [item.pathWithoutProject() for item in SideBarSelection(paths).getSelectedItems()]) else: print 'trying send to trash' try: for item in SideBarSelection(paths).getSelectedItemsWithoutChildItems(): if s.get('close_affected_buffers_when_deleting_even_if_dirty', False): item.close_associated_buffers() print 'closed associated buffers' print 'send2trash' send2trash(item.path()) SideBarProject().refresh(); print 'file deleted' print 'file exists?'+str(os.path.exists(item.path())) except: print 'something failed' print 'trying Permanent deletion' import functools self.window.run_command('hide_panel'); self.window.show_input_panel("Permanently Delete:", SideBarSelection(paths).getSelectedItems()[0].path(), functools.partial(self.on_done, SideBarSelection(paths).getSelectedItems()[0].path()), None, None)
def _send_path_to_trash(self, local_item_name, local_path): try: send2trash(local_path) self.items_store.delete_item(item_name=local_item_name, parent_path=self.remote_path) self.logger.debug('Delete untouched local item "%s" as it seems deleted remotely.', local_path) except (IOError, OSError) as e: self.logger.error('An error occurred when deleting untouched local item "%s": %s.', local_path, e)
def remove_file(self, file, message): to_trash = get_setting(self.window.active_view(), 'jekyll_send_to_trash', False) if to_trash: message = message + ( '\n\nYou seem to be using the `jekyll_send_to_trash` setting, so you ' 'can retrieve this file later in your system Trash or Recylcing Bin.' ) else: message = message + ( '\n\nThis action is permanent and irreversible since you are not using ' 'the `jekyll_send_to_trash` setting. Are you sure you want to continue?' ) delete = sublime.ok_cancel_dialog(message, 'Confirm Delete') if delete is True: self.window.run_command('close_file') self.window.run_command('refresh_folder_list') if to_trash: send2trash(file) else: os.remove(file) else: return
def trash(dst): """Moves given Objects to trash or unlinks symlinks""" if any([os.path.isfile(dst), os.path.isdir(dst)]): send2trash(dst) elif os.path.islink(dst): os.unlink(dst)
def clean(): from send2trash import send2trash _add, _parse, files = base_parser("Send folders and files to trash.") for file in files(no_subdir=True): print("delete", file) send2trash(str(file))
def scan(self, pyfile, thread): file = fs_encode(pyfile.plugin.last_download) filename = os.path.basename(pyfile.plugin.last_download) cmdfile = fs_encode(self.get_config('cmdfile')) cmdargs = fs_encode(self.get_config('cmdargs').strip()) if not os.path.isfile(file) or not os.path.isfile(cmdfile): return thread.addActive(pyfile) pyfile.setCustomStatus(_("virus scanning")) pyfile.setProgress(0) try: p = subprocess.Popen([cmdfile, cmdargs, file], bufsize=-1, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = map(str.strip, p.communicate()) if out: self.log_info(filename, out) if err: self.log_warning(filename, err) if not self.get_config('ignore-err'): self.log_debug("Delete/Quarantine task is aborted") return if p.returncode: pyfile.error = _("Infected file") action = self.get_config('action') try: if action == "Delete": if not self.get_config('deltotrash'): os.remove(file) else: try: send2trash.send2trash(file) except NameError: self.log_warning(_("Send2Trash lib not found, moving to quarantine instead")) pyfile.setCustomStatus(_("file moving")) shutil.move(file, self.get_config('quardir')) except Exception, e: self.log_warning(_("Unable to move file to trash: %s, moving to quarantine instead") % e.message) pyfile.setCustomStatus(_("file moving")) shutil.move(file, self.get_config('quardir')) else: self.log_debug("Successfully moved file to trash") elif action == "Quarantine": pyfile.setCustomStatus(_("file moving")) shutil.move(file, self.get_config('quardir')) except (IOError, shutil.Error), e: self.log_error(filename, action + " action failed!", e)
def delete_watched_episodes(): for episode in Episode.objects.filter(watched=True).exclude(filepath=""): if episode.show.auto_erase and episode.filepath: try: send2trash(episode.filepath) except OSError: pass episode.filepath = "" episode.save()
def clean_episode_db(): # print 'cleaning episode db...' if not os.path.exists(tv_shows_dir): return for episode in Episode.objects.all(): if not os.path.exists(episode.filepath) and episode.filepath: send2trash(episode.filepath) episode.filepath = "" episode.save()
def replace_application_in(applications_dir, always_yes=False, skip_app_from_appstore=True): ignores = parse_ignores(os.path.join(os.path.dirname(__file__), 'ignore.txt')) not_founded = [] installed_failed = [] send2trash_failed = [] try: applications = os.listdir(applications_dir) for application in applications: if application in ignores: continue application_path = os.path.join(applications_dir, application) if skip_app_from_appstore and\ is_installed_by_appstore(application_path): print('Skip {0} from Appstore'.format(application)) continue application_name, ext = os.path.splitext(application) if ext.lower() != '.app': continue application_name = generate_cask_token(application_path, application_name) try: cask_url = _CASKS_HOME + application_name + '.rb' application_info_file = urllib2.urlopen(cask_url, timeout=3) except Exception: not_founded.append(application) continue application_info = application_info_file.read() print('{0} -> {1}'.format(application, application_info)) if not always_yes: replace_it = input('Replace It(Y/n):') replace_it = replace_it.lower() if len(replace_it) > 0 and replace_it != 'y' and\ replace_it != 'yes': continue status = os.system('brew cask install {0}'. format(application_name)) if status != 0: installed_failed.append(application) else: try: send2trash(os.path.join(applications_dir, application)) except Exception: send2trash_failed.append(os.path.join(applications_dir, application)) finally: for x in not_founded: print('Not found: {0}'.format(x)) for x in installed_failed: print('Installed fail: {0}'.format(x)) for x in send2trash_failed: print('Send to trash fail: {0}'.format(x))
def save_all_wallpapers(self): for fname in os.listdir(self.directory): if fname.startswith('.'): continue full_name = os.path.join(self.directory, fname) try: shutil.move(full_name, os.path.dirname(self.directory)) except shutil.Error: #trying to save a wallpaper saved with self.save_wallpaper send2trash.send2trash(full_name)
'') #subtitle ARTSEEN shows, bold italic centered convertParaStyle('ARTSEEN_LEFT_TITLE ITALSHOW (ARTSEEN)', '#subtitleBoldCent#', '') #subtitle ARTSEEN shows, bold italic centered issueDocument.save('converted.docx') #convert to html print('Passing to mammoth') with open('converted.docx', 'rb') as docx_file: result = mammoth.convert_to_html(docx_file) html = result.value messages = result.messages print('File converted to html') send2trash.send2trash('converted.docx') #------------------------------------------------------------------------------------------------------ #start find and replace #------------------------------------------------------------------------------------------------------ print('Replacing Special Characters') html = html.replace( '</p><p>', '</p>\n\n<p>') #add new lines between paragraphs to aid readability #------------------------------------------------------------------------------------------------------ #convert <, >, and " from entities to characters to have functional html tags html = html.replace('<', '<') html = html.replace('>', '>')
#shutil.move('AdvancedPythonModules/practice.txt','../') print(os.listdir('AdvancedPythonModules/')) #Deleting a file print('****************DELETING FILES************************') #os.unlink(path) #Deletes the file at the path specified #os.rmdir(path) #Deletes a folder(folder must be empty) at the path provided #shutil.rmtree(path=) #Most dangerous. It will remove all the files and folders contained in the path # Once files or folders are deleted, these can't be recovered # Instead we can use send2trash module, which sends deleted files to trash bin instead of permanent removal import send2trash send2trash.send2trash('AdvancedPythonModules/practice.txt') print(os.listdir('AdvancedPythonModules/')) print('****************DIRECTORY TREE GENERATOR************************') #os.walk - returns a tuple with folder, sub folder and files within it file_path = '/Users/Parihar08/PycharmProjects/PythonJosePortilla/MilestoneProject2' for folder, subfolders, files in os.walk(file_path): print(f'Currently looking at: {folder}') print('\n') print('The Sub-Folders are: ') for sub_fold in subfolders: print(f'\t SubFolder: {sub_fold}') print('\n') print('The Files are: ') for f in files:
def delete_file(file_in): file_exists = os.path.isfile(file_in) if file_exists == True: send2trash.send2trash(file_in)
def move_album_art_files_to_album_dir(directory): art_directories = nested_album_art(directory) if art_directories["case1"]: print( f"Let's deal with {len(art_directories['case1'])} album art directories " "of first type") decision = prompt("Move all album art files to parent directory?", ["y", "n", "s", "q"]) if decision == "y": for art_dir in art_directories["case1"]: sub_dir = art_dir["art_dir"] parent = art_dir["parent_dir"] for filename in art_dir["art_files"]: ext = Path(filename).suffix name = Path(filename).name.replace(ext, "") old_path = os.path.join(sub_dir, filename) new_path = os.path.join(parent, filename) if name.isdigit(): print(f"Numeric art file name: {name} will rename to " f"'booklet-{filename}'") new_path = os.path.join(parent, f"booklet-{filename}") if os.path.exists(new_path): print(f"File already exists: {new_path}") old_size = Path(new_path).stat().st_size // 8 new_size = Path(old_path).stat().st_size // 8 if old_size != new_size: replace_decision = prompt( f"Replace '{new_path}' ({new_size} bytes) with " f"'{old_path}' ({old_size} bytes)?", ["d", "y", "n", "s", "q"], ) if replace_decision == "y": try: print(f"Moved '{new_path}' to trashbin") send2trash(new_path) os.rename(old_path, new_path) print( f"Moved '{old_path}' to '{new_path}'") except OSError as err: print(err) elif replace_decision == "d": send2trash(old_path) print(f"Moved '{old_path}' to trashbin") elif replace_decision == "q": print("Quit") sys.exit(0) elif replace_decision == "s": print("Skip this step") return else: continue else: send2trash(old_path) print( f"Moved '{old_path}' to trashbin as it's the same " "size as the file with the same name in the parent " "directory") else: try: os.rename(old_path, new_path) except OSError as err: print(err) leftover_files = [ f for f in os.listdir(sub_dir) if os.path.isfile(os.path.join(sub_dir, f)) ] if not leftover_files: send2trash(sub_dir) print(f"Moved empty art dir '{sub_dir}' to trashbin") else: print( f"There are still files in album art directory '{sub_dir}': " f"{leftover_files}") elif decision == "q": print("Quit") sys.exit(0) elif decision == "s": print("Skip this step") return else: print("No album art directories of first type! :)")
(\(\d\)) # Ex. would match (1) indicating the file has been downloaded more then once (.pptx|.docx|.jvl|.ppt|.doc) #pipe to match the match the various file extensions """, re.VERBOSE) #Step 2 create a folder to store the junk in, then move this folder to the trash newpath = r'/Users/coreygardner/Desktop/junkfolder' if not os.path.exists( newpath ): # Checks to see if the path exist, if it doesn't the new path is created os.makedirs(newpath) #Step 3: Walk the downloads folder and search the files downloads_folder = "/Users/coreygardner/Downloads" #creates variable storing download folder name for folderName, subfolders, filename in downloads_folder: mo = file_pattern.search(filename) if mo == None: continue # If search does not return anything then the program will just continue else: shutil.move( filename, newpath ) # will this take into account the filename without the entire path or will it automatically put the path in filename for folderName, subfolders, filename in newpath: send2trash.send2trash(newpath) else: print("Have a good day")
import os , shutil print(os.getcwd()) print(os.unlink())#Deletes but doesn't delete if dir has files print(shutil.rmtree('C:\\Users\\Ganesh\\Desktop\\Automate the Boring Stuff\\Files\\Text Files Backup')) import send2trash send2trash.send2trash('C:\\Users\\Ganesh\\Desktop\\Automate the Boring Stuff\\Files\\lalle2.txt')
assert os.path.isdir('new'), 'not folder' print(os.path.join(os.getcwd(), 'new')) print(os.path.abspath('.')) path_ = 'C:\\YandexDisk\\python\\Avtomamatizatsia\\new' print(os.path.isabs(path_)) path_ = 'new' print(os.path.isabs(path_)) print(os.path.relpath('C:\\Windows', 'C:\\egg\\spam')) print(os.path.realpath('C:Windows1/jhvjhv\\22222//lll')) paint = 'C:\\Windows\\system32\\mspaint.exe' print(os.path.dirname(paint)) print(os.path.basename(paint)) print(os.path.split(paint)) print(os.sep * 20) print(os.path.getsize(paint)) print(os.listdir('C:')) print(os.path.exists('C:\\F**K')) shutil.copy(paint, 'new\\mspaint.exe') shutil.move('new\\mspaint.exe', 'mspaint.exe') os.unlink('mspaint.exe') # del file os.rmdir('new') # del dir try: shutil.rmtree('xkcd') # del tree send2trash.send2trash('xkcd_T') # del trash except: pass
def uninstall(ext): send2trash(instance.extensionDir().absolutePath() + "/" + ext)
from PIL import Image import os import send2trash def splitImages(filename): im = Image.open(filename) newHeight = im.height / 20 total = 0 for i in range(1, 21): if i == 20: newImage = im.crop((0, total, im.width, im.height)) newImage.save(f'{filename}-20.jpg') else: newMaxHeight = total + newHeight newImage = im.crop((0, total, im.width, newMaxHeight)) total += newHeight newImage.save(f'{filename}-{i}.jpg') for i in os.listdir(): if os.path.isdir(i) == True: print(i) for j in os.listdir(i): splitImages(os.path.join(i, j)) send2trash.send2trash(os.path.join(i, j))
import send2trash baconFile = open('bacon.txt', 'a') baconFile.write('Bacon is not a vegetable.') baconFile.close() send2trash.send2trash('bacon.txt')
print('\n') if res.lower() == 'exit': # Выход в главное меню break elif res.lower( ) == 'back': # Подняться вверх по директории os.chdir('..') elif res.lower() == 'delete': # Команда удаления # Предупреждение об удалении print( 'Are you sure you want to send this folder to recycle bin? (YES/NO)' ) ans = input('Yes or No: ') if ans.lower() == 'yes' or 'y': path = os.getcwd() os.chdir('..') send2trash.send2trash(path) elif res in os.listdir(os.getcwd()): if os.path.isfile(res): # Предупреждение об удалении print( 'Are you sure you want to send this folder to recycle bin? (YES/NO)' ) ans = input('Yes or No: ') if ans.lower() == 'yes' or 'y': send2trash.send2trash(res) else: os.chdir(res) else: print('No file/folder exist of this name.') else: print('You chose wrong number')
async def delete_file(self, path): """Delete file at path.""" path = path.strip("/") os_path = self._get_os_path(path) rm = os.unlink if not os.path.exists(os_path): raise web.HTTPError( 404, u"File or directory does not exist: %s" % os_path) async def _check_trash(os_path): if sys.platform in {"win32", "darwin"}: return True # It's a bit more nuanced than this, but until we can better # distinguish errors from send2trash, assume that we can only trash # files on the same partition as the home directory. file_dev = (await run_sync(os.stat, os_path)).st_dev home_dev = (await run_sync(os.stat, os.path.expanduser("~"))).st_dev return file_dev == home_dev async def is_non_empty_dir(os_path): if os.path.isdir(os_path): # A directory containing only leftover checkpoints is # considered empty. cp_dir = getattr(self.checkpoints, "checkpoint_dir", None) dir_contents = set(await run_sync(os.listdir, os_path)) if dir_contents - {cp_dir}: return True return False if self.delete_to_trash: if (not self.always_delete_dir and sys.platform == "win32" and await is_non_empty_dir(os_path)): # send2trash can really delete files on Windows, so disallow # deleting non-empty files. See Github issue 3631. raise web.HTTPError(400, u"Directory %s not empty" % os_path) if await _check_trash(os_path): self.log.debug("Sending %s to trash", os_path) # Looking at the code in send2trash, I don't think the errors it # raises let us distinguish permission errors from other errors in # code. So for now, just let them all get logged as server errors. send2trash(os_path) return else: self.log.warning( "Skipping trash for %s, on different device " "to home directory", os_path, ) if os.path.isdir(os_path): # Don't permanently delete non-empty directories. if not self.always_delete_dir and await is_non_empty_dir(os_path): raise web.HTTPError(400, u"Directory %s not empty" % os_path) self.log.debug("Removing directory %s", os_path) with self.perm_to_403(): await run_sync(shutil.rmtree, os_path) else: self.log.debug("Unlinking file %s", os_path) with self.perm_to_403(): await run_sync(rm, os_path)
r'C:\Users\Dell\Downloads\eggs\jabuticaba2.txt') #apagando arquivos e pastas -> TOMAR CUIDADO AO EXECUTAR ISSO, PORQUE É PERMANENTE os.unlink( r'C:\Users\Dell\Downloads\eggs\jabuticaba.txt') #apaga arquivo em path os.rmdir(r'C:\Users\Dell\Downloads\eggs') #apaga pasta vazia shutil.rmtree( r'C:\Users\Dell\Downloads\eggs') #apaga pasta e arquivos nela contidos #send2trash para mandar para a lixeira e não apagar permanentemente import send2trash baconFile = open(r'C:\Users\Dell\Downloads\bacon.txt', 'a') baconFile.write('Bacon is not a vegetable.') baconFile.close() send2trash.send2trash(r'C:\Users\Dell\Downloads\bacon.txt') #os.walk para navegar por todas as pastas, subpastas e arquivos de um path for folderName, subfolders, filenames in os.walk(r'C:\Users\Dell\Downloads'): print('The current folder is ' + folderName) for subfolder in subfolders: print('SUBFOLDER OF ' + folderName + ': ' + subfolder) for filename in filenames: print('FILE INSIDE ' + folderName + ': ' + filename) #manipulando arquivos ZIP import zipfile ZipFile = zipfile.ZipFile(r"C:\Users\Dell\Downloads\TermsAndContracts.zip") ZipFile.namelist() info = ZipFile.getinfo('TermsAndContracts/bexs_agreement.pdf')
import send2trash baconFile = open('c:\\A\\bacon.txt', 'a') baconFile.write('Bacon is not vegetable.') baconFile.close() send2trash.send2trash('c:\\A\\bacon.txt')
# print("Files: " + str(files)) txt_writer.write("\n\nRoots: " + str(folder)) if len(subfolders) != 0: txt_writer.write("\nDirectories: " + str(subfolders)) if len(files) != 0: txt_writer.write("\nFiles: " + str(files)) for dir in subfolders: try: date = re.match(pattern=file_pattern, string=dir).group(1) if int(current_date)-int(date) > 7: dirs_to_remove.append(rf"{folder}\{dir}") except AttributeError: continue txt_writer.write(f"Directories to remove: {str(dirs_to_remove)}") return dirs_to_remove if __name__ == '__main__': ignore_directories = ["【Twitcasting Archive】", "【Member Stream】", "【Twitch】", "【Mildom】", "中岡TV。", "佐藤希Sato Nozomi"] # Number of days after which the directory should be remove(i.e.remove after 7 days) max_day = 7 arguments = checkArguments() dirs_to_remove = get_remove_directories(arguments, ignore_directories) print(dirs_to_remove) print(f"Removing {len(dirs_to_remove)} directories...") try: send2trash(dirs_to_remove) except Exception as e: print(e) input("Press Enter To Exit...")
def delunneed(path): for roots, dirs, files in os.walk(path): for f in files: if os.path.getsize(os.path.join(roots, f)) > 5 * 10**6: print('Send %s to trash bin.' % (os.path.join(roots, f))) send2trash.send2trash(os.path.join(roots, f))
# list subdirs modelruns = [d for d in os.listdir(modeldir) if d.startswith('run')] logruns = [d for d in os.listdir(logdir) if d.startswith('run')] bothruns = [d for d in modelruns if d in logruns] #intersection onlymodelruns = [d for d in modelruns if d not in bothruns] onlylogruns = [d for d in logruns if d not in bothruns] print('bothruns:', bothruns) print('onlymodelruns:', onlymodelruns) print('onlylogruns', onlylogruns) # delete folders w for d in onlymodelruns: print('Delete', path.join(modeldir, d)) if not dry: send2trash(path.join(modeldir, d)) #shutil.rmtree(path.join(modeldir, d)) for d in onlylogruns: print('Delete', path.join(logdir, d)) if not dry: send2trash(path.join(logdir, d)) #shutil.rmtree(path.join(logdir, d)) # delete runs without results minEpoch = 2 for d in bothruns: numEpoch = len(os.listdir(path.join(modeldir, d))) - 1 print('Run', d, 'contains', numEpoch, 'epochs') if numEpoch < minEpoch: print('Delete', path.join(modeldir, d)) if not dry:
# Builnding a list of all filenames and folder names files_or_folders = [f for f in listdir(my_path)] # Sorting the list by the creation time files_or_folders.sort(key=os.path.getctime, reverse=True) # Getting the current time into the variable 'now' in timeseries format now = datetime.datetime.now() # Get the files/folders creation time, and remove olders # Start by enumerating each item in the list for index, filename in enumerate(files_or_folders, start=0): ctime_file = time.ctime(os.path.getctime(my_path + filename)) ctime_file = datetime.datetime.strptime(ctime_file, "%a %b %d %H:%M:%S %Y") # get the time delta between the creation time and the current time difference_seconds = datetime.timedelta.total_seconds(now - ctime_file) difference_days = seconds_to_days(difference_seconds) # For debug (uncomment this to see what happens) # print(f'{index}. {filename}') if index >= 10: # for debug # print(f'{index}. {filename}') send2trash(my_path + files_or_folders[index]) else: if difference_days > 1: # For debug # print(f'diff: {difference_days}. {filename}') send2trash(my_path + files_or_folders[index])
) #can provide Absolute or releative paths os.rmdir( 'foldertoDelete' ) #will delete the given folder as it was created by above line it was empty #to delete The Folder with content import shutil #os.makedirs('S:\\Acadmecis College\\Placement\\pythonProgs1') #command to use for creating folder #shutil.rmtree('S:\\Acadmecis College\\Placement\\pythonProgs1') #will delete this folder #be careful while using these command this will remove folder permantly os.chdir('created\\folder\\using\\makedirs') for filename in os.listdir(): if filename.endswith('.d'): #print(filename) os.unlink(filename) #this command will delete all files with extension #here mydataNameChange.d got deleted #This above deletion is somewhat Dangerous cause can delete Imp files permanantly #so there is module which will delete to recycle bin only # that is send2trash import send2trash os.makedirs(os.path.join(os.getcwd(), 'foldertoDeleteUsingSend2Trash')) #creates folder #send2trash.send2trash('folderToDelete') send2trash.send2trash('foldertoDeleteUsingSend2Trash') #sends to Recycle Bin
eles somem. PARA RESOLVER ISSO, baixar : pip install send2trash """ # Importando a biblioteca send2trash from send2trash import send2trash # ABAIXO NÃO VAI PRA LIXEIRA APENAS SOME try: os.remove('exclui1.txt') # Não vai para lixeira, simplismente some except FileNotFoundError: print('ERRO - arquivo ja foi excluido, ou nome errad') # ABAIXO VAI PRA LIXEIRA, UTILIZANDO send2trash (BIBLIOTECA) try: send2trash('exclui2.txt') # Vai para lixeira except FileNotFoundError: print('ERRO - arquivo ja foi excluido e foi pra lixeira, ou nome errado') # Se o arquivo não existir teremos OS ERRO # Teste para ver se exclui diretorio para lixeira try: send2trash('oioi') # Vai para lixeira except FileNotFoundError: print('ERRO - arquivo ja foi excluido e foi pra lixeira') # send2trash envia arquivos e diretorios para a lixeira # ----------------------------------------------------------------
def what_to_do_with_cue(directory): cue_directories = cue_files_and_audio_files(directory) if not cue_directories: print(f"No cue files found in: {directory}") else: single_cue = [d for d in cue_directories if len(d.cues) == 1] multi_cue = [d for d in cue_directories if len(d.cues) > 1] print(f"Found {len(single_cue)} directories with single cue file & " f"{len(multi_cue)} directories with more than 1 cue file") decision = prompt("Proceed with cue clean-up?", ["y", "n", "q"]) if decision == "y": print( "Let's start with directories containing more than 1 cue file") for cue_dir in multi_cue: print( f"\n\nThere are {len(cue_dir.audio_files)} audio files in " f"{cue_dir.dir} and {len(cue_dir.cues)} CUE files") for f in sorted(cue_dir.audio_files): print(f"* {f}") for cue_file in cue_dir.cues: cue_path = os.path.join(cue_dir.dir, cue_file) cue = CueParser(cue_path) if "FILE" in cue.meta: print( f"'{cue_file}' refers to {len(cue.tracks)} tracks in 1 " f"file: {cue.meta['FILE']}") else: print( f"'{cue_file}' refers to {len(cue.tracks)} tracks in " f"{len(set(t['FILE'] for t in cue.tracks))} file(s)" ) print( "Files:\n*", "\n* ".join( set( t.get("FILE", "NO FILE ENTRY!!!") for t in sorted(cue.tracks, key=lambda t: t["FILE"]))), ) print( "Titles:\n*", "\n* ".join( t.get("TITLE", "NO TITLE ENTRY!!!") for t in sorted(cue.tracks, key=lambda t: t["TRACK_NUM"])), ) for cue_file in cue_dir.cues: cue_path = os.path.join(cue_dir.dir, cue_file) cue_decision = prompt( f"What do you want to do with '{cue_file}'?", ["d", "p", "s", "q"], ) if cue_decision == "d": send2trash(cue_path) print(f"Moved '{cue_path}' to trash bin") elif cue_decision == "p": cmd = f"flacon -s '{cue_path}'" return_code, std = process_command(cmd) if return_code == 0: print( f"Flacon successfully processed '{cue_path}'") deleted_cue_decision = prompt( f"Delete '{cue_file}' and source audio?", ["d", "n", "s", "q"], ) if deleted_cue_decision in ["d", "y"]: cue_path = os.path.join(cue_dir.dir, cue_file) cue = CueParser(cue_path) cue_audio_file = (cue.meta.get("FILE").replace( " ", "_").lower()) cue_audio_file_path = os.path.join( cue_dir.dir, cue_audio_file) if not os.path.exists(cue_audio_file_path): print( f"Couldn't find audio file '{cue_audio_file}'" f" specified in '{cue_file}'") for audio_file in cue_dir.audio_files: delete_entry_audio_file = prompt( "Delete '{audio_file}' and source audio?", ["d", "s", "q"], ) if delete_entry_audio_file == "y": audio_file_path = os.path.join( cue_dir, audio_file) send2trash(audio_file_path) print( "Successfully deleted audio source " f"file: {audio_file}") else: send2trash(cue_audio_file_path) print( "Successfully deleted audio source file: " f"{cue_audio_file}") send2trash(cue_path) print( f"Successfully deleted cue file: {cue_file}" ) elif cue_decision == "q": print("Quit") sys.exit(0) else: print(f"Skipped '{cue_file}'") continue else: print( f"Flacon had some issues with '{cue_path}': {std}" ) elif cue_decision == "q": print("Quit") sys.exit(0) else: print(f"Skipped '{cue_path}'") continue print("Let's now deal with directories with single cue file") cues_to_split = [] cues_to_delete = [] min_audio_files = 1 for cue_dir in single_cue: cue_file = cue_dir.cues[0] cue_path = os.path.join(cue_dir.dir, cue_file) cue = CueParser(cue_path) files_equal_tracks = len(cue_dir.audio_files) == len( cue.tracks) more_files_than_min = len( cue_dir.audio_files) > min_audio_files if files_equal_tracks and more_files_than_min: cues_to_delete.append(cue_dir) else: cues_to_split.append(cue_dir) assert len(cues_to_delete) + len(cues_to_split) == len(single_cue) if cues_to_delete: print( f"Found {len(cues_to_delete)} cue files with more than " f"{min_audio_files} track that looks to be already extracted" ) for cue_dir in cues_to_delete: cue_file = cue_dir.cues[0] cue_path = os.path.join(cue_dir.dir, cue_file) cue = CueParser(cue_path) print( f"\n\nThere are {len(cue_dir.audio_files)} audio files in " f"{cue_dir.dir}") for f in sorted(cue_dir.audio_files): print(f"* {f}") print( "CUE Titles:\n*", "\n* ".join( f'{t.get("TRACK_NUM")} - {t.get("TITLE", "NO TITLE ENTRY")}' for t in sorted(cue.tracks, key=lambda t: t["TRACK_NUM"])), ) delete_extracted_cues = prompt( f"Delete '{len(cues_to_delete)}' already extracted CUE files?", ["d", "s", "q"], ) if delete_extracted_cues in ["d", "y"]: for cue_dir in cues_to_delete: cue_file = cue_dir.cues[0] cue_path = os.path.join(cue_dir.dir, cue_file) send2trash(cue_path) print(f"Deleted {len(cues_to_delete)} extracted CUE files") elif delete_extracted_cues == "q": print("Quit") sys.exit(0) else: print(f"Skipped '{cue_file}'") if cues_to_split: for cue_dir in cues_to_split: cue_file = cue_dir.cues[0] cue_path = os.path.join(cue_dir.dir, cue_file) cue = CueParser(cue_path) print(f"\n\nOnly {len(cue_dir.audio_files)} audio file " f"'{cue_dir.audio_files[0]}' in '{cue_dir.dir}'") print( f"Looks like it should be split into {len(cue.tracks)} tracks " f"defined in '{cue_file}':") print( "CUE Tracks:\n*", "\n* ".join( f'{t.get("TRACK_NUM")} - {t.get("TITLE", "NO TITLE ENTRY")}' for t in sorted(cue.tracks, key=lambda t: t["TRACK_NUM"])), ) cue_decision = prompt( "Would you like to split those cue files with Flacon and delete " "them afterwards?", ["p", "s", "q"], ) if cue_decision == "p": for cue_dir in cues_to_split: cue_file = cue_dir.cues[0] cue_path = os.path.join(cue_dir.dir, cue_file) cue = CueParser(cue_path) cmd = f"flacon -s '{cue_path}'" return_code, std = process_command(cmd) if return_code == 0: print( f"Flacon successfully processed '{cue_path}'") cue_audio_file = (cue.meta.get("FILE").replace( " ", "_").lower()) cue_audio_file_path = os.path.join( cue_dir.dir, cue_audio_file) if os.path.exists(cue_audio_file_path): send2trash(cue_audio_file_path) print( "Successfully deleted audio source file: " f"{cue_audio_file}") send2trash(cue_path) print( f"Successfully deleted cue file: {cue_file}" ) else: print( f"Couldn't find audio file '{cue_audio_file}' " f"specified in '{cue_file}'") for audio_file in cue_dir.audio_files: audio_file_path = os.path.join( cue_dir.dir, audio_file) send2trash(audio_file_path) print( "Successfully deleted audio source file: " f"{audio_file}") send2trash(cue_path) print( f"Successfully deleted cue file: {cue_file}" ) else: print( f"Flacon had some issues with '{cue_path}': {std}" ) elif cue_decision == "q": print("Quit") sys.exit(0) else: print(f"Skipped '{cue_path}'") print("Cleaned up all directories with cue files") elif decision == "q": print("Quit") sys.exit(0) else: print("Skipped cleaning up directories with cue files")
def image_delete(self): l.log("delete: " + self._all_images[self._current_index]) send2trash(self._all_images[self._current_index]) self._all_images.remove(self._all_images[self._current_index]) self._set_image(self._current_index)
def remove_file(self, filepath): return send2trash(filepath)
import zipfile, shutil, pprint, os workingDir = '/home/xiaodong/Gitroot/automationwithpython/chapter9' pathForZip = '/home/xiaodong/Gitroot/automationwithpython/chapter9/demoFolder' zipFileName = 'example' os.chdir(workingDir) # move to the folder with example.zip # make zip file shutil.make_archive(zipFileName, 'zip', pathForZip) # read zip file and list directory and files exampleZip = zipfile.ZipFile(zipFileName + '.zip') pprint.pprint(exampleZip.namelist()) # get specific file information spamInfo = exampleZip.getinfo('bacon1.txt') print(spamInfo.file_size) print(spamInfo.compress_size) exampleZip.close() #make the cleaning by sending the zipfile to trash import send2trash send2trash.send2trash(zipFileName + '.zip')
def delete_zip(path): for filename in os.listdir(path): if filename.endswith('.zip') and filename.startswith('Play'): send2trash.send2trash(filename) return
def perform_move_to_trash(self, paths, description): # TODO: do it with subprocess dialog import send2trash for path in paths: send2trash.send2trash(path)
def remove(self, name): p = self.profileFolder() if os.path.exists(p): send2trash(p) self.db.execute("delete from profiles where name = ?", name) self.db.commit()
def trashCollection(self): p = self.collectionPath() if os.path.exists(p): send2trash(p)
def folderCreate(selectTuple): if selectTuple[1] == 'delete': send2trash.send2trash('./' + selectTuple[0]) os.makedirs('./' + selectTuple[0])
def main(): """The entry point to ARC, to start the evolutionary approach.""" restart = False # 1. Set config._ROOT_DIR - as it is needed by everything! if config._ROOT_DIR != os.path.split(os.getcwd())[0] + os.sep: logger.info("Configuring _ROOT_DIR in config.py") configRoot = fileinput.FileInput(files=('config.py'), inplace=1) for line in configRoot: if line.find("_ROOT_DIR =") is 0: line = "_ROOT_DIR = \"{}\" ".format( os.path.split(os.getcwd())[0] + os.sep) print( line[0:-1] ) # Remove extra newlines (a trailing-space must exists in modified lines) configRoot.close() restart = True if restart: print("Config's _ROOT_DIR changed to {}. Restarting.".format( config._ROOT_DIR)) logger.info("Config's _ROOT_DIR changed to {}. Restarting.".format( config._ROOT_DIR)) python = sys.executable os.execl(python, python, *sys.argv) # 2. With _ROOT_DIR configured, we can determine the operating system, # config._OS we are running on. # One way to do this is to use the 'uname' command: # - On Linux, 'uname -o' returns 'GNU/Linux' # - On Mac, 'uname -o' isn't recognized. 'uname' returns 'Darwin' # Check for the workarea directory if not os.path.exists(config._PROJECT_DIR): os.makedirs(config._PROJECT_DIR) outFile = tempfile.SpooledTemporaryFile() errFile = tempfile.SpooledTemporaryFile() helpProcess = subprocess.Popen(['uname', '-o'], stdout=outFile, stderr=errFile, cwd=config._PROJECT_DIR, shell=False) helpProcess.wait() outFile.seek(0) outText = outFile.read() outFile.close() ourOS = 0 # 10 is Mac, 20 is Linux if re.search("Linux", outText): ourOS = 20 # Linux else: ourOS = 10 # Mac # 3. Set config._OS restart = False logger.info("Configuring _OS in config.py") if (config._OS == "MAC" and ourOS == 20) or (config._OS == "LINUX" and ourOS == 10): configOS = fileinput.FileInput(files=('config.py'), inplace=1) for line in configOS: if line.find("_OS =") is 0 or line.find("_OS=") is 0: if ourOS == 10: # Mac line = "_OS = \"MAC\" " # Note the extra space at the end else: # Linux line = "_OS = \"LINUX\" " print( line[0:-1] ) # Remove extra newlines (a trailing-space must exists in modified lines) configOS.close() restart = True if restart: if ourOS == 20: outText = "Linux" else: outText = "MAC" print("Config's _OS changed to {}. Restarting.".format(outText)) logger.info("Config's _OS changed to {}. Restarting.".format(outText)) python = sys.executable os.execl(python, python, *sys.argv) # 4. Compile the project if os.path.exists(config._PROJECT_DIR): shutil.rmtree(config._PROJECT_DIR) shutil.copytree(config._PROJECT_PRISTINE_DIR, config._PROJECT_DIR) txl_operator.compile_project() # 5. Set up ConTest (Thread noising tool) contester.setup() # 6. Set up Chord (A static analysis tool) static.setup() # 7. Acquire classpath dynamically using 'ant test' if config._PROJECT_CLASSPATH is None: outFile = tempfile.SpooledTemporaryFile() errFile = tempfile.SpooledTemporaryFile() antProcess = subprocess.Popen(['ant', '-v', config._PROJECT_TEST], stdout=outFile, stderr=errFile, cwd=config._PROJECT_DIR, shell=False) antProcess.wait() outFile.seek(0) outText = outFile.read() outFile.close() # If you are getting an error at the re.search below, make sure the ant # build file has the following sections. _PROJECT_PRISTINE_SRC_DIR and # related entries in config.py have to agree with what is in the ant file: # <path id="classpath.base"> # <pathelement location="${current}" /> # <pathelement location="${build.classes}" /> # <pathelement location="${src.main}" /> # </path> # <path id="classpath.test"> # <pathelement location="../lib/junit-4.8.1.jar" /> # <pathelement location="${tst-dir}" /> # <path refid="classpath.base" /> # </path> # <target name="test" depends="compile" > # <junit fork="yes"> # <!-- THE TEST SUITE FILE--> # <test name = "Cache4jTest"/> # <!-- NEED TO BE THE CLASS FILES (NOT ABSOLUTE) --> # <classpath refid="classpath.test"/> # <formatter type="plain" usefile="false" /> <!-- to screen --> # </junit> # </target> config._PROJECT_CLASSPATH = re.search( "-classpath'\s*\[junit\]\s*'(.*)'", outText).groups()[0] # 8. Acquire dynamic timeout value from ConTest contestTime = contester.run_test_execution(20) # Too many runs is overkill #contestTime = contester.run_test_execution(config._CONTEST_RUNS * # config._CONTEST_VALIDATION_MULTIPLIER) config._CONTEST_TIMEOUT_SEC = contestTime * config._CONTEST_TIMEOUT_MULTIPLIER logger.info("Using a timeout value of {}s".format( config._CONTEST_TIMEOUT_SEC)) # 9. Clean up the temporary directory (Probably has subdirs from previous runs) logger.info("Cleaning TMP directory") # Cleaning up a previous run could take half an hour on the mac # (10,000+ files is slow) # Trying an alternate approach: Sending the files to the trash # Using an external module, Send2Trash from: # https://pypi.python.org/pypi/Send2Trash # Install command: pip install Send2Trash # Some info on pip at: https://pypi.python.org/pypi if not os.path.exists(config._TMP_DIR): os.makedirs(config._TMP_DIR) else: send2trash(config._TMP_DIR) #shutil.rmtree(config._TMP_DIR) Native python, slow os.makedirs(config._TMP_DIR) # We're keeping a database (config file) containing the results # of previous static analysis runs. Check it first. if not static.find_static_in_db(config._PROJECT_TESTSUITE): static.configure_chord() static.run_chord_datarace() static.get_chord_targets() static.load_contest_list() static.get_synch_vars_from_functions() static.eliminate_primitives() static.create_final_triple() # Write the discovered values to file right away. The # final values are written in the finally block of # evolution.start() at the end of the run. if len(static._classVar) > 0 or len(static._classMeth) > 0 \ or len(static._classMethVar) > 0: static.write_static_to_db(config._PROJECT_TESTSUITE) # 11. Start the main bug-fixing procedure evolution.start()