Stat_Geek/Delete all labels ( SAS)
/*This line of code deletes all variable labels, so that only variable names will show*/ attrib _all_ label='';
sastechies/SAS Macro to create a delimited text /csv file from a SAS data set.. ( SAS)
/*Lets take an example*/
options source mprint;
data one;
input id name :$20. amount ;
date=today();
format amount dollar10.2 date mmddyy10.;
label id="Customer ID Number";
datalines;
1 Grant 57.23
2 Michael 45.68
3 Tammy 53.21
;
run;
%macro makefile
(
dataset=_last_ , /* Dataset to write */
filename=print , /* File to write to */
dlmr="," , /* Delimiter between values */
qtes="no" , /* Should SAS quote all character variables? */
header="no" , /* Do you want a header line w/ column names? */
label="no" /* Should labels be used instead of var names in header? */
);
proc contents data=&dataset out=___out_;run;
/* Return to orig order */
proc sort data=___out_;
by varnum;
run;
/* Build list of variable names */
data _null_;
set ___out_ nobs=count;
call symput("name"!!left(put(_n_,3.)),name);
call symput("type"!!left(put(_n_,3.)),type);
/* Use var name when label not present */
if label=" " then label=name;
call symput("lbl"!!left(put(_n_,3.)),label);
if _n_=1 then call symput("numvars", trim(left(put(count, best.))));
run;
/*Remove the temporary contents dataset created above*/
proc datasets lib=work nolist;
delete ___out_;
quit;
/* Create file */
data _null_;
set &dataset;
file &filename;
%global temp;
%if &qtes="yes" %then %let temp='"';
%else %let temp=' ';
%if &header="yes" %then
%do;
/* Conditionally add column names */
if _n_=1 then
do;
put %if &label="yes" %then
%do;
%do i=1 %to &numvars-1;
&temp "%trim(%bquote(&&lbl&i)) " +(-1) &temp &dlmr
%end;
&temp "%trim(%bquote(&&lbl&numvars)) " &temp;
%end;
%else
%do;
%do i=1 %to &numvars-1;
&temp "%trim(&&name&i) " +(-1) &temp &dlmr
%end;
&temp "%trim(&&name&numvars) " &temp ;
%end;
end;
%end;
/* Build PUT stmt to write values */
put
%do i = 1 %to &numvars -1;
%if &&type&i ne 1 and &qtes="yes" %then
%do;
'"' &&name&i +(-1) '"' &dlmr
%end;
%else
%do;
&&name&i +(-1) &dlmr
%end;
%end;
%if &&type&i ne 1 and &qtes="yes" %then
%do;
/* Write last varname */
'"' &&name&numvars +(-1) '"';
%end;
%else
%do;
/* Write last varname */
&&name&numvars;
%end;
run;
%mend makefile;
/* If LRECL= required because of records longer the 256, specify here */
filename mycsv "C:\csvdata.txt" lrecl=1000;
filename mypipe "C:\pipedata.txt" lrecl=1000;
filename mypipe2 "C:\pipedata2.txt" lrecl=1000;
/* Invoke macro to write to a file, include proper parameters for your case. */
/* Make sure that the variables are in the order you want and have the */
/* desired formats. */
%makefile(dataset=one,
filename=mycsv, /* FILEREF or DDNAME of the file */
dlmr=",",
qtes="yes",
header="yes",
label="yes");
%makefile(dataset=one,
filename=mypipe, /* FILEREF or DDNAME of the file */
dlmr="|",
qtes="yes",
header="yes",
label="yes");
%makefile(dataset=one,
filename=mypipe2, /* FILEREF or DDNAME of the file */
dlmr="|",
qtes="no",
header="yes",
label="yes");
sastechies/SAS Macro to Cleanup your WORK directory ( SAS)
%macro CleanupWORK(membertype);
/***
ACCESS - access descriptor files (created by SAS/ACCESS software)
ALL - all member types
CATALOG- SAS catalogs
DATA - SAS data files
FDB - financial database
MDDB - multidimensional database
PROGRAM - stored compiled SAS programs
VIEW - SAS views
****/
%let validvals=ACCESS ALL CATALOG DATA FDB MDDB PROGRAM VIEW;
%if %index(&validvals,%upcase(&membertype)) gt 0 %then
%do;
proc datasets lib=WORK kill nolist memtype=%upcase(&membertype);
quit;
%end;
%mend;
/* Want to delete all Work Datasets*/
%CleanupWORK(data);
%CleanupWORK(CATALOG);
sarathannapareddy/How to delete previously assigned formats and informats of variables in the dataset ( SAS)
check out the comple article and diff. ways of doing this at: http://studysas.blogspot.com/2009/05/how-to-delete-or-remove-previously.html
How to delete previously assigned formats and informats completely from the SAS dataset:
PROC DATASETS lib=work; MODIFY dsn; FORMAT all; INFORMAT all; RUN; QUIT;
sarathannapareddy/How to delete or remove previously assigned formats and informats completely from the SAS dataset: ( SAS)
PROC DATASETS lib=work; MODIFY dsn; FORMAT _all_; INFORMAT _all_; RUN; QUIT; *work is the library name; *mention the name of the SAS dataset, whose formats and informats needs to be removed in the MODIFY statement; * format _all_ will delete all the formats in the SAS dataset. contd......
webonomic/Send SAS Data to Excel ( SAS)
/* This program writes a SAS Data Set to EXCEL using DBLOAD */ proc dbload dbms=xls data=sasuser.houses; path=’c:\path\to\my\folder\filename.xls’; putnames=yes; label; reset all; limit=0; load; run;
webonomic/Show all possible values in table regardless of whether or not the value exists ( SAS)
/* Given the following Data: */
data test;
input var1 var2 var3;
datalines;
. 2 .
. 2 1
0 2 1
0 2 1
1 2 1
1 2 1
1 3 1
3 3 5
3 3 5
3 3 5
3 4 5
3 4 5
5 4 5
;
run;
/* Solution #1: Proc Tabulate */
data dummy;
input var1 var2 var3;
cards;
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
;
run;
proc format;
value var_fmt
0="N/A"
1="Very Poor"
2="Poor"
3="Average"
4="Good"
5="Very Good"
;
run;
quit;
data joined;
set test(in=is_valid) dummy;
if is_valid then valid=1;
run;
%macro doit;
%DO I=1 %TO 3;
proc tabulate data=joined format=8.;
class var&I;
var valid;
tables var&I, valid=' '*n=' '
/ rts=22 misstext='0';
title 'Title Here';
format var&I var_fmt.;
label var&I="Var&I Label Here";
run;
%END;
%mend;
%doit;
/* Solution #2: Proc Summary + Proc Freq Combo */
proc format;
value var_fmt
.="Missing"
0="N/A"
1="Very Poor"
2="Poor"
3="Average"
4="Good"
5="Very Good"
;
run;
quit;
proc summary nway completetypes missing;
class var1--var3 / preloadfmt;
format var1--var3 var_fmt.;
output out=count(drop=_type_);
run;
proc freq data=count;
tables var1--var3 / list nocum;
format var1--var3 var_fmt.;
weight _freq_ / zeros;
run;
Here are two solutions when creating a table to show responses to a questionnaire where respondents rate items in various categories. In this case, the responses range from 0 to 5 (N/A, Very Poor, Poor, Average, Good, Very Good).
statsplank/SAS program top ( SAS)
%let Root=Z; options nodate nonumber; libname p "&Root:\Feb08\sas\pathways"; goptions reset=all htitle=3 htext=3 ftext=swiss ftitle=swiss; axis1 label=(a=90 f=swiss h=3) minor=none w=2 major=(h=2 w=2); axis2 label=(f=swiss h=3) minor=none w=2 major=(h=1.5 w=2);
Stephen Chappell/Directory Pruner 3 ( python)
################################################################################
# Directory Pruner 3.pyw
################################################################################
package = __import__('Directory Pruner 3') # Get the source package of program.
package.main() # Call the main entry point to the Directory Pruner application.
################################################################################
# __init__.py
################################################################################
#! /usr/bin/env python
"""Module providing GUI capability to prune any directory.
The code presented in this module is for the purposes of: (1) ascertaining
the space taken up by a directory, its files, its sub-directories, and its
sub-files; (2) allowing for the removal of the sub-files, sub-directories,
files, and directory found in the first purpose; (3) giving the user a GUI
to accomplish said purposes in a convenient way that is easily accessible."""
################################################################################
__author__ = 'Stephen "Zero" Chappell <Noctis.Skytower@gmail.com>'
__date__ = '21 February 2011'
__version__ = '$Revision: 418 $'
################################################################################
import base64
import os
import time
import tkinter
import zlib
from . import view
from . import widgets
################################################################################
ICON = b'eJxjYGAEQgEBBiApwZDBzMAgxsDAoAHEQCEGBQaIOAwkQDE2UOSkiUM\
Gp/rlyd740Ugzf8/uXROxAaA4VvVAqcfYAFCcoHqge4hR/+btWwgCqoez8aj//fs\
XWiAARfCrhyCg+XA2HvV/YACoHs4mRj0ywKWe1PD//p+B4QMOmqGeMAYAAY/2nw=='
################################################################################
def main():
"Create an application containing a single TrimDir widget."
tkinter.NoDefaultRoot()
root = create_application_root()
attach_window_icon(root, ICON)
view = setup_class_instance(root)
main_loop(root)
def create_application_root():
"Create and configure the main application window."
root = widgets.Tk()
root.minsize(430, 215)
root.title('Directory Pruner')
root.option_add('*tearOff', tkinter.FALSE)
return root
def attach_window_icon(root, icon):
"Generate and use the icon in the window's corner."
with open('tree.ico', 'wb') as file:
file.write(zlib.decompress(base64.b64decode(ICON)))
root.iconbitmap('tree.ico')
os.remove('tree.ico')
def setup_class_instance(root):
"Build TrimDir instance that expects resizing."
instance = view.TrimDir(root)
instance.grid(row=0, column=0, sticky=tkinter.NSEW)
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
return instance
def main_loop(root):
"Process all GUI events according to tkinter's settings."
target = time.clock()
while True:
try:
root.update()
except tkinter.TclError:
break
target += tkinter._tkinter.getbusywaitinterval() / 1000
time.sleep(max(target - time.clock(), 0))
################################################################################
# Directory Pruner 3/animator.py
################################################################################
#! /usr/bin/env python
"""Module for animating and displaying error messages.
The indicate_error function is the only available function in this module.
Calling it with the appropriate arguments should display an error for you."""
################################################################################
__author__ = 'Stephen "Zero" Chappell <Noctis.Skytower@gmail.com>'
__date__ = '21 February 2011'
__version__ = '$Revision: 1 $'
################################################################################
import _tkinter
import math
################################################################################
def indicate_error(root, alternative, callback, force=False):
"Prepare to shake the application's root window."
if force:
_tkinter.setbusywaitinterval(20)
elif _tkinter.getbusywaitinterval() != 20:
# Show error message if not running at 50 FPS.
alternative.show()
return callback()
root.after_idle(_shake, root, callback)
def _shake(root, callback, frame=0):
"Animate each step of shaking the root window."
frame += 1
# Get the window's location and update the X position.
x, y = map(int, root.geometry().split('+')[1:])
x += round(math.sin(math.pi * frame / 2.5) * \
math.sin(math.pi * frame / 50) * 5)
root.geometry('+{}+{}'.format(x, y))
if frame < 50:
# Schedule next step in the animation.
root.after(20, _shake, root, callback, frame)
else:
# Enable operations after one second.
callback()
################################################################################
# Directory Pruner 3/bytesize.py
################################################################################
#! /usr/bin/env python
"""Module for converting byte to strings and vice versa.
Various function are provided for changing byte sizes into English words.
If the conversion is exact, the string may also be converted into a number."""
################################################################################
__author__ = 'Stephen "Zero" Chappell <Noctis.Skytower@gmail.com>'
__date__ = '21 February 2011'
__version__ = '$Revision: 1 $'
################################################################################
import math
################################################################################
# Provide a way of converting byte sizes into strings.
def convert(number):
"Convert bytes into human-readable representation."
if not number:
return '0 Bytes'
if not 0 < number < 1 << 110:
raise ValueError('Number out of range!')
ordered = reversed(tuple(format_bytes(partition_number(number, 1 << 10))))
cleaned = ', '.join(item for item in ordered if item[0] != '0')
return cleaned
def partition_number(number, base):
"Continually divide number by base until zero."
div, mod = divmod(number, base)
yield mod
while div:
div, mod = divmod(div, base)
yield mod
def format_bytes(parts):
"Format partitioned bytes into human-readable strings."
for power, number in enumerate(parts):
yield '{} {}'.format(number, format_suffix(power, number))
def format_suffix(power, number):
"Compute the suffix for a certain power of bytes."
return (PREFIX[power] + 'byte').capitalize() + ('s' if number != 1 else '')
PREFIX = ' kilo mega giga tera peta exa zetta yotta bronto geop'.split(' ')
################################################################################
# Define additional operations for the TreeviewNode class.
def parse(string):
"Convert human-readable string back into bytes."
total = 0
for part in string.split(', '):
number, unit = part.split(' ')
s = number != '1' and 's' or ''
for power, prefix in enumerate(PREFIX):
if unit == (prefix + 'byte' + s).capitalize():
break
else:
raise ValueError('{!r} not found!'.format(unit))
total += int(number) * 1 << 10 * power
return total
def abbr(number):
"Convert bytes into abbreviated representation."
# Check value of number before processing.
if not number:
return '0 Bytes'
if not 0 < number < (1 << 100) * 1000:
raise ValueError('Number out of range!')
# Calculate range of number and correct value.
level = int(math.log(number) / math.log(1 << 10))
value = number / (1 << 10 * level)
# Move to the next level if number is high enough.
if value < 1000:
precision = 4
else:
precision = 3
level += 1
value /= 1 << 10
# Format the number before returning to caller.
if level:
result = '{:.{}}'.format(value, precision)
return '{} {}'.format(result, format_suffix(level, result == '1.0'))
return '{} {}'.format(int(value), format_suffix(level, value))
################################################################################
# Directory Pruner 3/discover.py
################################################################################
#! /usr/bin/env python
"""Module for mapping out directory sizes.
Creating a SizeTree instance will automatically discover the directory size.
The directory's structure will be accessible through the tree-like structure."""
################################################################################
__author__ = 'Stephen "Zero" Chappell <Noctis.Skytower@gmail.com>'
__date__ = '21 February 2011'
__version__ = '$Revision: 1 $'
################################################################################
import os
################################################################################
class SizeTree:
"Create a tree structure outlining a directory's size."
__slots__ = 'name path children file_size total_size total_nodes'.split()
def __init__(self, path, callback=None):
"Initialize the SizeTree object and search the path while updating."
# Validate the search's current progress.
if callback is not None:
callback()
head, tail = os.path.split(path)
# Create attributes for this instance.
self.name = tail or head
self.path = path
self.children = []
self.file_size = 0
self.total_size = 0
self.total_nodes = 0
# Try searching this directory.
try:
dir_list = os.listdir(path)
except OSError:
pass
else:
# Examine each object in this directory.
for name in dir_list:
path_name = os.path.join(path, name)
if os.path.isdir(path_name):
# Create child nodes for subdirectories.
size_tree = SizeTree(path_name, callback)
self.children.append(size_tree)
self.total_size += size_tree.total_size
self.total_nodes += size_tree.total_nodes + 1
elif os.path.isfile(path_name):
# Try getting the size of files.
try:
self.file_size += os.path.getsize(path_name)
except OSError:
pass
# Add in the total file size to the total size.
self.total_size += self.file_size
def pop_child(self, name):
"Return a named child or None if not found."
for index, child in enumerate(self.children):
if child.name == name:
return self.children.pop(index)
########################################################################
def __str__(self):
"Return a representation of the tree formed by this object."
lines = [self.path]
self.__walk(lines, self.children, '')
return '\n'.join(lines)
@classmethod
def __walk(cls, lines, children, prefix):
"Generate lines based on children and keep track of prefix."
dir_prefix, walk_prefix = prefix + '+---', prefix + '| '
for pos, neg, child in cls.__enumerate(children):
if neg == -1:
dir_prefix, walk_prefix = prefix + '\\---', prefix + ' '
lines.append(dir_prefix + child.name)
cls.__walk(lines, child.children, walk_prefix)
@staticmethod
def __enumerate(sequence):
"Generate positive and negative indices for sequence."
length = len(sequence)
for count, value in enumerate(sequence):
yield count, count - length, value
################################################################################
# Directory Pruner 3/remove.py
################################################################################
#! /usr/bin/env python
"""Module for removing files and directories.
These functions help in removing directories and files by various methods.
The core of the context menu is implemented by the provided capabilities."""
################################################################################
__author__ = 'Stephen "Zero" Chappell <Noctis.Skytower@gmail.com>'
__date__ = '21 February 2011'
__version__ = '$Revision: 1 $'
################################################################################
import os
################################################################################
def directory_files(path, remove_directory=False, remove_path=False):
"Remove directory at path, respecting the flags."
for root, dirs, files in os.walk(path, False):
# Ignore path if remove_path is false.
if remove_path or root != path:
for name in files:
filename = os.path.join(root, name)
try:
os.remove(filename)
except OSError:
pass
# Ignore directory if remove_directory is false.
if remove_directory:
try:
os.rmdir(root)
except OSError:
pass
def files(path):
"Remove files in path and get remaining space."
total_size = 0
# Find all files in directory of path.
for name in os.listdir(path):
pathname = os.path.join(path, name)
if os.path.isfile(pathname):
# Try to remove any file that may have been found.
try:
os.remove(pathname)
except OSError:
# If there was an error, try to get the filesize.
try:
total_size += os.path.getsize(pathname)
except OSError:
pass
# Return best guess of space still occupied.
return total_size
def empty_directories(path, remove_root=False, recursive=True):
"Remove all empty directories while respecting the flags."
if recursive:
for name in os.listdir(path):
try:
empty_directories(os.path.join(path, name), True)
except OSError:
pass
if remove_root:
os.rmdir(path)
def empty_files(path, recursive=True):
"Remove all files that are empty of any contents."
for root, dirs, files in os.walk(path):
if not recursive:
del dirs[:]
for name in files:
filename = os.path.join(root, name)
try:
if not os.path.getsize(filename):
os.remove(filename)
except OSError:
pass
################################################################################
# Directory Pruner 3/runmethod.py
################################################################################
#! /usr/bin/env python
"""Module executing same method on tuple items.
The Apply class can store items and run the same method on all objects.
Results are returned as a tuple, and exeception are raised when needed."""
################################################################################
__author__ = 'Stephen "Zero" Chappell <Noctis.Skytower@gmail.com>'
__date__ = '21 February 2011'
__version__ = '$Revision: 1 $'
################################################################################
class Apply(tuple):
"Create a container that can run a method from its contents."
def __getattr__(self, name):
"Get a virtual method to map and apply to the contents."
return self.__Method(self, name)
########################################################################
class __Method:
"Provide a virtual method that can be called on the array."
def __init__(self, array, name):
"Initialize the method with array and method name."
self.__array = array
self.__name = name
def __call__(self, *args, **kwargs):
"Execute method on contents with provided arguments."
name, error, buffer = self.__name, False, []
for item in self.__array:
attr = getattr(item, name)
try:
data = attr(*args, **kwargs)
except Exception as problem:
error = problem
else:
if not error:
buffer.append(data)
if error:
raise error
return tuple(buffer)
################################################################################
# Directory Pruner 3/scheduler.py
################################################################################
#! /usr/bin/env python
"""Module for scheduling execution on single thread.
This is the core of the GUI's ability to run in a multi-threaded environment.
Calling run on a class instance ensures execution on the creating thread."""
################################################################################
__author__ = 'Stephen "Zero" Chappell <Noctis.Skytower@gmail.com>'
__date__ = '21 February 2011'
__version__ = '$Revision: 1 $'
################################################################################
import _thread
import functools
import queue
import warnings
################################################################################
class Affinity:
"Predecessor to AffinityLoop that might not return results."
__slots__ = '__action', '__thread'
def __init__(self):
"Initialize Affinity with job queue and thread identity."
self.__action = queue.Queue()
self.__thread = _thread.get_ident()
def run(self, func, *args, **keywords):
"Try to run function with arguments on the creating thread."
self.__action.put_nowait(functools.partial(func, *args, **keywords))
if _thread.get_ident() == self.__thread:
problem = False
while not self.__action.empty():
delegate = self.__action.get_nowait()
try:
data = delegate()
except Exception as error:
problem = error
if problem:
raise problem
return data
warnings.warn('Affinity did not return!')
################################################################################
class AffinityLoop:
"Restricts code execution to thread that instance was created on."
__slots__ = '__action', '__thread'
def __init__(self):
"Initialize AffinityLoop with job queue and thread identity."
self.__action = queue.Queue()
self.__thread = _thread.get_ident()
def run(self, func, *args, **keywords):
"Run function on creating thread and return result."
if _thread.get_ident() == self.__thread:
self.__run_jobs()
return func(*args, **keywords)
else:
job = self.__Job(func, args, keywords)
self.__action.put_nowait(job)
return job.result
def __run_jobs(self):
"Run all pending jobs currently in the job queue."
while not self.__action.empty():
job = self.__action.get_nowait()
job.execute()
########################################################################
class __Job:
"Store information to run a job at a later time."
__slots__ = ('__func', '__args', '__keywords',
'__error', '__mutex', '__value')
def __init__(self, func, args, keywords):
"Initialize the job's info and ready for execution."
self.__func = func
self.__args = args
self.__keywords = keywords
self.__error = False
self.__mutex = _thread.allocate_lock()
self.__mutex.acquire()
def execute(self):
"Run the job, store any error, and return to sender."
try:
self.__value = self.__func(*self.__args, **self.__keywords)
except Exception as error:
self.__error = True
self.__value = error
self.__mutex.release()
@property
def result(self):
"Return execution result or raise an error."
self.__mutex.acquire()
if self.__error:
raise self.__value
return self.__value
################################################################################
# Directory Pruner 3/threadlog.py
################################################################################
#! /usr/bin/env python
"""Module for starting threads that have their errors logged.
The start_thread function is the only procedure for use in this module.
When threads are started, errors will be automatically written to a file."""
################################################################################
__author__ = 'Stephen "Zero" Chappell <Noctis.Skytower@gmail.com>'
__date__ = '21 February 2011'
__version__ = '$Revision: 1 $'
################################################################################
import _thread
import logging
import os
import sys
import traceback
################################################################################
def start_thread(function, *args, **kwargs):
"Start a new thread and wrap with error catching."
_thread.start_new_thread(_bootstrap, (function, args, kwargs))
def _bootstrap(function, args, kwargs):
"Run function with arguments and log any errors."
try:
function(*args, **kwargs)
except Exception:
basename = os.path.basename(sys.argv[0])
filename = os.path.splitext(basename)[0] + '.log'
logging.basicConfig(filename=filename)
logging.error(traceback.format_exc())
################################################################################
# Directory Pruner 3/treeview.py
################################################################################
#! /usr/bin/env python
"""Module for manipulating nodes in a treeview.
The Node class provides a high-level interface to work with treeview nodes.
When creating a Node instance, a Treeview instance must should be wrapped."""
################################################################################
__author__ = 'Stephen "Zero" Chappell <Noctis.Skytower@gmail.com>'
__date__ = '21 February 2011'
__version__ = '$Revision: 1 $'
################################################################################
import sys
import tkinter
from .bytesize import convert, parse, abbr
from .view import TrimDir
################################################################################
class Node:
"Interface to allow easier interaction with Treeview instance."
@classmethod
def current(cls, tree):
"Take a tree view and return its currently selected node."
node = tree.selection()
return cls(tree, node[0] if node else node)
########################################################################
# Standard Treeview Operations
__slots__ = '__tree', '__node'
def __init__(self, tree, node=''):
"Initialize the Node object (root if node not given)."
self.__tree = tree
self.__node = node
def __str__(self):
"Return a string representation of this node."
return '''\
NODE: {!r}
Name: {}
Total Size: {}
File Size: {}
Path {}\
'''.format(self.__node, self.name, self.total_size, self.file_size, self.path)
def insert(self, position, text):
"Insert a new node with text at position in current node."
node = self.__tree.insert(self.__node, position, text=text)
# PATCH: Store extra data about node.
if TrimDir.SIZE:
self.__tree.nodes[node] = dict()
return Node(self.__tree, node)
def append(self, text):
"Add a new node with text to the end of this node."
return self.insert(tkinter.END, text)
def move(self, parent, index):
"Insert this node under parent at index."
self.__tree.move(self.__node, parent, index)
def reattach(self, parent='', index=tkinter.END):
"Attach node to parent at index (defaults to end of root)."
self.move(parent, index)
def detach(self):
"Unlink this node from its parent but do not delete."
self.__tree.detach(self.__node)
def delete(self, get_parent=False, from_tree=True): # Internal Last Flag
"Delete this node (optionally, return parent)."
if self.__tree.exists(self.__node):
parent = self.parent if get_parent else None
# PATCH: Remove extra data about node.
if TrimDir.SIZE:
for child in self.children:
child.delete(from_tree=False)
del self.__tree.nodes[self.__node]
if from_tree:
self.__tree.delete(self.__node)
#=====================================
return parent
if get_parent:
raise ValueError('Cannot return parent!')
########################################################################
# Standard Treeview Properties
@property
def root(self):
"Return if this is the root node."
return self.__node == ''
@property
def parent(self):
"Return the parent of this node."
return Node(self.__tree, self.__tree.parent(self.__node))
@property
def level(self):
"Return number of levels this node is under root."
count, node = 0, self
while not node.root:
node = node.parent
count += 1
return count
@property
def position(self):
"Return the position of this node in its parent."
return self.__tree.index(self.__node)
@property
def expanded(self):
"Return whether or not the node is current open."
value = self.__tree.item(self.__node, 'open')
return bool(value) and value.string == 'true'
@property
def children(self):
"Yield back each child of this node."
for child in self.__tree.get_children(self.__node):
yield Node(self.__tree, child)
########################################################################
# Custom Treeview Properties
# (specific for application)
@property
def name(self):
"Return the name of this node (tree column)."
return self.__tree.item(self.__node, 'text')
# PATCH: Custom Size
if TrimDir.SIZE:
# Shortened Byte Size
def __get_total_size(self):
return self.__tree.nodes[self.__node][TrimDir.CLMS[0]]
def __set_total_size(self, value):
self.__tree.nodes[self.__node][TrimDir.CLMS[0]] = value
self.__tree.set(self.__node, TrimDir.CLMS[0], abbr(value))
def __get_file_size(self):
return self.__tree.nodes[self.__node][TrimDir.CLMS[1]]
def __set_file_size(self, value):
self.__tree.nodes[self.__node][TrimDir.CLMS[1]] = value
self.__tree.set(self.__node, TrimDir.CLMS[1], abbr(value))
else:
# Complete Byte Size
def __get_total_size(self):
return parse(self.__tree.set(self.__node, TrimDir.CLMS[0]))
def __set_total_size(self, value):
self.__tree.set(self.__node, TrimDir.CLMS[0], convert(value))
def __get_file_size(self):
return parse(self.__tree.set(self.__node, TrimDir.CLMS[1]))
def __set_file_size(self, value):
self.__tree.set(self.__node, TrimDir.CLMS[1], convert(value))
#=========================================================================
def __get_path(self):
return self.__tree.set(self.__node, TrimDir.CLMS[2])
def __set_path(self, value):
self.__tree.set(self.__node, TrimDir.CLMS[2], value)
total_size = property(__get_total_size, __set_total_size,
doc="Total size of this node (first column)")
file_size = property(__get_file_size, __set_file_size,
doc="File size of this node (second column)")
path = property(__get_path, __set_path,
doc="Path of this node (third column)")
########################################################################
# Custom Treeview Sort Order
# (specific for application)
def sort_name(self):
"If the node is open, sort its children by name."
self.__sort(lambda child: child.name)
def sort_total_size(self):
"If the node is open, sort its children by total size."
self.__sort(lambda child: child.total_size)
def sort_file_size(self):
"If the node is open, sort its children by file size."
self.__sort(lambda child: child.file_size)
def sort_path(self):
"If the node is open, sort its children by path."
self.__sort(lambda child: child.path)
def __sort(self, key):
"Sort an expanded node's children by the given key."
if self.expanded:
nodes = list(self.children)
order = sorted(nodes, key=key)
if order == nodes:
order = reversed(order)
for child in order:
self.__tree.move(child.__node, self.__node, tkinter.END)
################################################################################
# Directory Pruner 3/view.py
################################################################################
#! /usr/bin/env python
"""Module containing main GUI class of application.
The overly large TrimDir class is the main interface to this program.
To use Directory Pruner in other programs, create and use TrimDir objects."""
################################################################################
__author__ = 'Stephen "Zero" Chappell <Noctis.Skytower@gmail.com>'
__date__ = '21 February 2011'
__version__ = '$Revision: 1 $'
################################################################################
import os
import tkinter
from . import animator
from . import discover
from . import remove
from . import runmethod
from . import threadlog
from . import widgets
################################################################################
class TrimDir(widgets.Frame):
"Widget for examining size of directory with optional deletion."
WARN = True # Should warnings be made for permanent operations?
MENU = True # Should the (destructive) context menu be enabled?
SIZE = True # Should directory sizes be patched for less words?
# Give names to columns.
CLMS = 'total_size', 'file_size', 'path'
TREE = '#0'
########################################################################
# Initialize the TrimDir object.
__slots__ = ('__tk', '__label', '__path', '__run', '__cancel',
'__progress', '__tree', '__scroll_1', '__scroll_2',
'__grip', '__menu', '__dialog', '__error', '__warn')
def __init__(self, master=None, **kw):
"Initialize the TrimDir instance and configure for operation."
super().__init__(master, **kw)
# Initialize and configure this frame widget.
self.capture_root()
self.create_widgets()
self.create_supports()
self.create_bindings()
self.configure_grid()
self.configure_tree()
self.configure_menu()
# Set focus to path entry.
self.__path.focus_set()
def capture_root(self):
"Capture the root (Tk instance) of this application."
widget = self.master
while not isinstance(widget, widgets.Tk):
widget = widget.master
self.__tk = widget
def create_widgets(self):
"Create all the widgets that will be placed in this frame."
self.__label = widgets.Button(self, text='Path:', command=self.choose)
self.__path = widgets.Entry(self, cursor='xterm')
self.__run = widgets.Button(self, text='Search', command=self.search)
self.__cancel = widgets.Button(self, text='Cancel',
command=self.stop_search)
self.__progress = widgets.Progressbar(self, orient=tkinter.HORIZONTAL)
self.__tree = widgets.Treeview(self, columns=self.CLMS,
selectmode=tkinter.BROWSE)
self.__scroll_1 = widgets.Scrollbar(self, orient=tkinter.VERTICAL,
command=self.__tree.yview)
self.__scroll_2 = widgets.Scrollbar(self, orient=tkinter.HORIZONTAL,
command=self.__tree.xview)
self.__grip = widgets.Sizegrip(self)
def create_supports(self):
"Create all GUI elements not placed directly in this frame."
self.__menu = widgets.Menu(self)
self.create_directory_browser()
self.create_error_message()
self.create_warning_message()
def create_directory_browser(self):
"Find root of file system and create directory browser."
head, tail = os.getcwd(), True
while tail:
head, tail = os.path.split(head)
self.__dialog = widgets.Directory(self, initialdir=head)
def create_error_message(self):
"Create error message when trying to search bad path."
options = {'title': 'Path Error',
'icon': tkinter.messagebox.ERROR,
'type': tkinter.messagebox.OK,
'message': 'Directory does not exist.'}
self.__error = widgets.Message(self, **options)
def create_warning_message(self):
"Create warning message for permanent operations."
options = {'title': 'Important Warning',
'icon': tkinter.messagebox.QUESTION,
'type': tkinter.messagebox.YESNO,
'message': '''\
You cannot undo these operations.
Are you sure you want to do this?'''}
self.__warn = widgets.Message(self, **options)
def create_bindings(self):
"Bind the widgets to any events they will need to handle."
self.__label.bind('<Return>', self.choose)
self.__path.bind('<Control-Key-a>', self.select_all)
self.__path.bind('<Control-Key-/>', lambda event: 'break')
self.__path.bind('<Return>', self.search)
self.__run.bind('<Return>', self.search)
self.__cancel.bind('<Return>', self.stop_search)
self.bind_right_click(self.__tree, self.open_menu)
@staticmethod
def select_all(event):
"Select all of the contents in this Entry widget."
event.widget.selection_range(0, tkinter.END)
return 'break'
def bind_right_click(self, widget, action):
"Bind action to widget while considering Apple computers."
if self.__tk.tk.call('tk', 'windowingsystem') == 'aqua':
widget.bind('<2>', action)
widget.bind('<Control-1>', action)
else:
widget.bind('<3>', action)
def configure_grid(self):
"Place all widgets on the grid in their respective locations."
self.__label.grid(row=0, column=0)
self.__path.grid(row=0, column=1, sticky=tkinter.EW)
self.__run.grid(row=0, column=2, columnspan=2)
self.__run.grid_remove()
self.__cancel.grid(row=0, column=2, columnspan=2)
self.__cancel.grid_remove()
self.__run.grid()
self.__progress.grid(row=1, column=0, columnspan=4, sticky=tkinter.EW)
self.__tree.grid(row=2, column=0, columnspan=3, sticky=tkinter.NSEW)
self.__scroll_1.grid(row=2, column=3, sticky=tkinter.NS)
self.__scroll_2.grid(row=3, column=0, columnspan=3, sticky=tkinter.EW)
self.__grip.grid(row=3, column=3, sticky=tkinter.SE)
# Configure the grid to automatically resize internal widgets.
self.grid_rowconfigure(2, weight=1)
self.grid_columnconfigure(1, weight=1)
def configure_tree(self):
"Configure the Treeview widget."
# Setup the headings.
self.__tree.heading(self.TREE, text=' Name', anchor=tkinter.W,
command=self.sort_name)
self.__tree.heading(self.CLMS[0], text=' Total Size', anchor=tkinter.W,
command=self.sort_total_size)
self.__tree.heading(self.CLMS[1], text=' File Size', anchor=tkinter.W,
command=self.sort_file_size)
self.__tree.heading(self.CLMS[2], text=' Path', anchor=tkinter.W,
command=self.sort_path)
# Setup the columns.
self.__tree.column(self.TREE, minwidth=100, width=200)
self.__tree.column(self.CLMS[0], minwidth=100, width=200)
self.__tree.column(self.CLMS[1], minwidth=100, width=200)
self.__tree.column(self.CLMS[2], minwidth=100, width=200)
# Connect the Scrollbars.
self.__tree.configure(yscrollcommand=self.__scroll_1.set)
self.__tree.configure(xscrollcommand=self.__scroll_2.set)
# PATCH: Provide data store.
if TrimDir.SIZE:
self.__tree.nodes = dict()
def configure_menu(self):
"Configure the (context) Menu widget."
# Shortcut for narrowing the search.
self.__menu.add_command(label='Search Directory',
command=self.search_dir)
self.__menu.add_separator()
# Operations committed on directory.
self.__menu.add_command(label='Remove Directory', command=self.rm_dir)
self.__menu.add_command(label='Remove Files', command=self.rm_files)
self.__menu.add_separator()
# Operations that recurse on sub-directories.
self.__menu.add_command(label='Remove Sub-directories',
command=self.rm_subdirs)
self.__menu.add_command(label='Remove Sub-files',
command=self.rm_subfiles)
self.__menu.add_separator()
# Operations that remove empty directories and files.
self.__menu.add_command(label='Remove Empty Directories',
command=self.rm_empty_dirs)
self.__menu.add_command(label='Remove Empty Files',
command=self.rm_empty_files)
# Only add "Open Directory" command on Windows.
if hasattr(os, 'startfile'):
self.__menu.add_separator()
self.__menu.add_command(label='Open Directory',
command=self.open_dir)
########################################################################
# This property is used to control access to operations.
def __get_operations_enabled(self):
"Return if run button is in normal state."
return self.__run['state'].string == tkinter.NORMAL
def __set_operations_enabled(self, value):
"Enable or disable run button's state according to value."
self.__run['state'] = tkinter.NORMAL if value else tkinter.DISABLED
operations_enabled = property(__get_operations_enabled,
__set_operations_enabled,
doc="Flag controlling certain operations")
########################################################################
# Handle path browsing and searching actions.
def choose(self, event=None):
"Show directory browser and set path as needed."
path = self.__dialog.show()
if path:
# Entry is cleared before absolute path is added.
self.__path.delete(0, tkinter.END)
self.__path.insert(0, os.path.abspath(path))
def search(self, event=None):
"Start search thread while GUI automatically updates."
threadlog.start_thread(self.search_thread)
def search_thread(self):
"Search the path and display the size of the directory."
if self.operations_enabled:
self.operations_enabled = False
# Get absolute path and check existence.
path = os.path.abspath(self.__path.get())
if os.path.isdir(path):
# Enable operations after finishing search.
self.__search(path)
self.operations_enabled = True
else:
animator.indicate_error(self.__tk, self.__error,
self.enable_operations)
def __search(self, path):
"Execute the search procedure and display in Treeview."
self.__run.grid_remove()
self.__cancel.grid()
children = self.start_search()
try:
tree = discover.SizeTree(path, self.validate_search)
except StopIteration:
self.handle_stop_search(children)
else:
self.finish_search(children, tree)
self.__cancel.grid_remove()
self.__run.grid()
########################################################################
# Execute various phases of a search.
def start_search(self):
"Edit the GUI in preparation for executing a search."
self.__stop_search = False
children = runmethod.Apply(treeview.Node(self.__tree).children)
children.detach()
self.__progress.configure(mode='indeterminate', maximum=100)
self.__progress.start()
return children
def validate_search(self):
"Check that the current search action is valid."
if self.__stop_search:
self.__stop_search = False
raise StopIteration('Search has been canceled!')
def stop_search(self, event=None):
"Cancel a search by setting its stop flag."
self.__stop_search = True
def handle_stop_search(self, children):
"Reset the Treeview and Progressbar on premature termination."
children.reattach()
self.__progress.stop()
self.__progress['mode'] = 'determinate'
def finish_search(self, children, tree):
"Delete old children, update Progressbar, and update Treeview."
children.delete()
self.__progress.stop()
self.__progress.configure(mode='determinate',
maximum=tree.total_nodes+1)
node = treeview.Node(self.__tree).append(tree.name)
try:
self.build_tree(node, tree)
except StopIteration:
pass
########################################################################
# Handle Treeview column sorting events initiated by user.
def sort_name(self):
"Sort children of selected node by name."
treeview.Node.current(self.__tree).sort_name()
def sort_total_size(self):
"Sort children of selected node by total size."
treeview.Node.current(self.__tree).sort_total_size()
def sort_file_size(self):
"Sort children of selected node by file size."
treeview.Node.current(self.__tree).sort_file_size()
def sort_path(self):
"Sort children of selected node by path."
treeview.Node.current(self.__tree).sort_path()
########################################################################
# Handle right-click events on the Treeview widget.
def open_menu(self, event):
"Select Treeview row and show context menu if allowed."
item = event.widget.identify_row(event.y)
if item:
event.widget.selection_set(item)
if self.menu_allowed:
self.__menu.post(event.x_root, event.y_root)
@property
def menu_allowed(self):
"Check if menu is enabled along with operations."
return self.MENU and self.operations_enabled
def search_dir(self):
"Search the path of the currently selected row."
path = treeview.Node.current(self.__tree).path
self.__path.delete(0, tkinter.END)
self.__path.insert(0, path)
self.search()
def rm_dir(self):
"Remove the currently selected directory."
if self.commit_permanent_operation:
threadlog.start_thread(self.do_remove_directory)
def rm_files(self):
"Remove the files in the currently selected directory."
if self.commit_permanent_operation:
threadlog.start_thread(self.do_remove_files)
def rm_subdirs(self):
"Remove the sub-directories of the currently selected directory."
if self.commit_permanent_operation:
threadlog.start_thread(self.do_remove_subdirectories)
def rm_subfiles(self):
"Remove the sub-files of the currently selected directory."
if self.commit_permanent_operation:
threadlog.start_thread(self.do_remove_subfiles)
def rm_empty_dirs(self):
"Recursively remove empty directories from selected directory."
if self.commit_permanent_operation:
threadlog.start_thread(self.do_remove_empty_dirs)
def rm_empty_files(self):
"Recursively remove empty files from selected directory."
if self.commit_permanent_operation:
threadlog.start_thread(self.do_remove_empty_files)
@property
def commit_permanent_operation(self):
"Check if warning should be issued before committing operation."
return not self.WARN or self.__warn.show() == tkinter.messagebox.YES
def open_dir(self):
"Open up the current directory (only available on Windows)."
os.startfile(treeview.Node.current(self.__tree).path)
########################################################################
# Execute actions requested by context menu.
def do_remove_directory(self):
"Remove a directory and all of its sub-directories."
self.begin_rm()
# Get the current Treeview node and delete it.
node = treeview.Node.current(self.__tree)
directory_size, path = node.total_size, node.path
position, parent = node.position, node.delete(True)
# Delete the entire directory at path.
remove.directory_files(path, True, True)
if os.path.isdir(path):
# Add the directory back to the Treeview.
tree = discover.SizeTree(path)
self.begin_rm_update(tree.total_nodes + 1)
# Rebuild the Treeview under the parent.
node = parent.insert(position, tree.name)
self.build_tree(node, tree)
# New directory size.
total_size = tree.total_size
else:
self.begin_rm_update()
# New directory size.
total_size = 0
# If the size has changed, update parent nodes.
if directory_size != total_size:
diff = total_size - directory_size
self.update_parents(parent, diff)
self.end_rm()
def do_remove_files(self):
"Remove all of the files in the selected directory."
# Delete files in the directory and get its new size.
node = treeview.Node.current(self.__tree)
total_size = remove.files(node.path)
# Update current and parent nodes if the size changed.
if node.file_size != total_size:
diff = total_size - node.file_size
node.file_size = total_size
node.total_size += diff
self.update_parents(node.parent, diff)
def do_remove_subdirectories(self):
"Remove all subdirectories in the directory."
self.begin_rm()
# Remove all the children nodes in Viewtree.
node = treeview.Node.current(self.__tree)
for child in node.children:
child.delete()
# Delete all of the subdirectories and their files.
remove.directory_files(node.path, True)
# Find out what subdirectories could not be deteled.
tree = discover.SizeTree(node.path)
self.begin_rm_update(tree.total_nodes)
if tree.total_nodes:
# Rebuild the Viewtree as needed.
self.build_tree(node, tree, False)
# Fix node and prepare to update parents.
diff = node.total_size - tree.total_size
node.total_size = tree.total_size
else:
# Fix node and prepare to update parents.
diff = node.file_size - node.total_size
node.total_size = node.file_size
# Update parents with new size.
self.update_parents(node.parent, diff)
self.end_rm()
def do_remove_subfiles(self):
"Remove all subfiles while keeping subdirectories in place."
self.begin_rm()
node = treeview.Node.current(self.__tree)
remove.directory_files(node.path)
self.synchronize_tree(node)
def do_remove_empty_dirs(self):
"Remove all empty directories from selected directory."
self.begin_rm()
node = treeview.Node.current(self.__tree)
remove.empty_directories(node.path)
self.synchronize_tree(node)
def do_remove_empty_files(self):
"Remove all empty files from selected directory."
self.begin_rm()
# Remove empty files from the current path.
node = treeview.Node.current(self.__tree)
remove.empty_files(node.path)
# Return the Progressbar back to normal.
self.begin_rm_update()
self.end_rm()
########################################################################
# Help update Progressbar in removal process.
def begin_rm(self):
"Start a long-running removal operation."
self.operations_enabled = False
self.__progress.configure(mode='indeterminate', maximum=100)
self.__progress.start()
def begin_rm_update(self, nodes=0):
"Move to determinate mode of updating the Viewtree."
self.__progress.stop()
self.__progress.configure(mode='determinate', maximum=nodes)
def end_rm(self):
"Finish removal process by enabling operations."
self.operations_enabled = True
enable_operations = end_rm # Create alias for command.
########################################################################
# Update the Viewtree nodes after creating a SizeTree object.
def synchronize_tree(self, node):
"Find the current directory state and update the tree."
# Build a new SizeTree to find the result.
tree = discover.SizeTree(node.path)
self.begin_rm_update(tree.total_nodes)
# Record the difference and patch the Viewtree.
diff = tree.total_size - node.total_size
self.patch_tree(node, tree)
# Fix all parent nodes with the correct size.
self.update_parents(node.parent, diff)
self.end_rm()
def build_tree(self, node, tree, update_node=True):
"Build the Treeview while updating the Progressbar."
self.validate_search()
if update_node:
self.sync_nodes(node, tree)
self.add_children(node, tree)
def sync_nodes(self, node, tree):
"Update attributes on node and refresh GUI."
# Copy the information on the node.
node.total_size = tree.total_size
node.file_size = tree.file_size
node.path = tree.path
# Update the Progressbar and GUI.
self.__progress.step()
################################################################################
# Directory Pruner 3/widgets.py
################################################################################
#! /usr/bin/env python
"""Module for thread-safe GUI widget library.
The _ThreadSafe base class is provides a foundation for the other widgets.
Support for more widgets can be easily added by adding more definitions."""
################################################################################
__author__ = 'Stephen "Zero" Chappell <Noctis.Skytower@gmail.com>'
__date__ = '21 February 2011'
__version__ = '$Revision: 1 $'
################################################################################
import operator
import tkinter.filedialog
import tkinter.messagebox
import tkinter.ttk
from . import scheduler
################################################################################
class _ThreadSafe:
"Create a thread-safe GUI class for safe cross-threaded calls."
ROOT = tkinter.Tk
def __init__(self, master=None, *args, **keywords):
"Initialize a thread-safe wrapper around a GUI base class."
if master is None:
if self.BASE is not self.ROOT:
raise ValueError('Widget must have a master!')
# Use Affinity() if it does not break.
self.__job = scheduler.AffinityLoop()
self.__schedule(self.__initialize, *args, **keywords)
else:
self.master = master
self.__job = master.__job
self.__schedule(self.__initialize, master, *args, **keywords)
def __initialize(self, *args, **keywords):
"Delegate instance creation to later time if necessary."
self.__obj = self.BASE(*args, **keywords)
########################################################################
# Provide a framework for delaying method execution when needed.
def __schedule(self, *args, **keywords):
"Schedule execution of a method till later if necessary."
return self.__job.run(self.__run, *args, **keywords)
@classmethod
def __run(cls, func, *args, **keywords):
"Execute the function after converting the arguments."
args = tuple(cls.unwrap(i) for i in args)
keywords = dict((k, cls.unwrap(v)) for k, v in keywords.items())
return func(*args, **keywords)
@staticmethod
def unwrap(obj):
"Unpack inner objects wrapped by _ThreadSafe instances."
return obj.__obj if isinstance(obj, _ThreadSafe) else obj
########################################################################
# Allow access to and manipulation of wrapped instance's settings.
def __getitem__(self, key):
"Get a configuration option from the underlying object."
return self.__schedule(operator.getitem, self, key)
def __setitem__(self, key, value):
"Set a configuration option on the underlying object."
return self.__schedule(operator.setitem, self, key, value)
########################################################################
# Create attribute proxies for methods and allow their execution.
def __getattr__(self, name):
"Create a requested attribute and return cached result."
attr = self.__Attr(self.__callback, (name,))
setattr(self, name, attr)
return attr
def __callback(self, path, *args, **keywords):
"Schedule execution of named method from attribute proxy."
return self.__schedule(self.__method, path, *args, **keywords)
def __method(self, path, *args, **keywords):
"Extract a method and run it with the provided arguments."
method = self.__obj
for name in path:
method = getattr(method, name)
return method(*args, **keywords)
########################################################################
class __Attr:
"Save an attribute's name and wait for execution."
__slots__ = '__callback', '__path'
def __init__(self, callback, path):
"Initialize proxy with callback and method path."
self.__callback = callback
self.__path = path
def __call__(self, *args, **keywords):
"Run a known method with the given arguments."
return self.__callback(self.__path, *args, **keywords)
def __getattr__(self, name):
"Generate a proxy object for a sub-attribute."
if name in {'__func__', '__name__'}:
# Hack for the "tkinter.__init__.Misc._register" method.
raise AttributeError('This is not a real method!')
return self.__class__(self.__callback, self.__path + (name,))
################################################################################
# Provide thread-safe classes to be used from tkinter.
class Tk(_ThreadSafe): BASE = tkinter.Tk
class Frame(_ThreadSafe): BASE = tkinter.ttk.Frame
class Button(_ThreadSafe): BASE = tkinter.ttk.Button
class Entry(_ThreadSafe): BASE = tkinter.ttk.Entry
class Progressbar(_ThreadSafe): BASE = tkinter.ttk.Progressbar
class Treeview(_ThreadSafe): BASE = tkinter.ttk.Treeview
class Scrollbar(_ThreadSafe): BASE = tkinter.ttk.Scrollbar
class Sizegrip(_ThreadSafe): BASE = tkinter.ttk.Sizegrip
class Menu(_ThreadSafe): BASE = tkinter.Menu
class Directory(_ThreadSafe): BASE = tkinter.filedialog.Directory
class Message(_ThreadSafe): BASE = tkinter.messagebox.Message
def patch_tree(self, node, tree):
"Patch differences between node and tree."
node.total_size = tree.total_size
node.file_size = tree.file_size
self.patch_children(node, tree)
self.add_children(node, tree)
def add_children(self, node, tree):
"Build and traverse all child nodes."
for child in tree.children:
subnode = node.append(child.name)
self.build_tree(subnode, child)
def patch_children(self, node, tree):
"Patch Viewtree based on children of SizeTree."
for subnode in node.children:
child = tree.pop_child(subnode.name)
if child is None:
# Directory is gone.
subnode.delete()
else:
# Dig down further in tree.
self.__progress.step()
self.patch_tree(subnode, child)
@staticmethod
def update_parents(node, diff):
"Add in difference to node and parents."
while not node.root:
node.total_size += diff
node = node.parent
################################################################################
# TrimDir must already exist.
from . import treeview
After considering the monolithic design of recipe 577633 and deciding that it should be divided into several smaller modules, Directory Pruner 3 was written to take advantage of better abstraction methodologies. There are a total of twelve files in the project, and all of them except the first are contained within a directory called "Directory Pruner 3" such that they make up a package in Python. Like the other Directory Pruners, please use and configure this program at your own computer's risk.
If you have any comments or wish to vote this recipe down, please provide an explanation as to what you find fault with in this program and also a solution that you would implement to fix the problem.
karlhorky/Test webpage for all common xhtml tags ( XHTML)
<!DOCTYPE html> <html lang="en"> <head> <title> Title </title> </head> <body> <div id="content"> <div id="content-body"> <h1>Content Types Examples - h1</h1> <p> Sed dignissim, neque ac malesuada eleifend, diam dolor ullamcorper nulla, et venenatis lectus justo et urna. Nulla facilisi. Suspendisse nec justo at tortor feugiat convallis. Donec quis ligula turpis. Proin posuere erat quis augue placerat non mattis nisl condimentum. </p> <h2>Paragraphs and General Formatting - h2</h2> <p> Vivamus sit amet <a href="#">link</a> tortor. Sed condimentum, <em>em (emphasis)</em>, nulla turpis tincidunt dui, non <strong>strong</strong> ut erat. Tristique felis. Nam sit amet <cite>cite (citation)</cite> viverra, metus sed cursus dignissim, <dfn>dfn (definition)</dfn> mauris, lobortis elit massa ut risus. Suspendisse semper ornare elit ac sagittis. Nunc id <del>del (deleted)</del> <ins>ins (inserted)</ins> at at ligula. In lacus dui, lacinia eget adipiscing id, <span>span</span> cursus in erat<sub>sub (subscript)</sub>. Proin<sup>sup (superscript)</sup> et massa mauris. </p> <blockquote> Blockquote text: Curabitur sed odio eu lacus volutpat hendrerit eu in justo. Etiam vitae orci nunc. Phasellus egestas auctor urna, tristique vestibulum elit consequat vel. Aliquam erat volutpat. Vivamus eu odio at orci dignissim dignissim ac quis diam. Sed dui nisl, laoreet vel viverra sit amet, interdum eget risus. Vivamus ut augue a eros pellentesque dapibus. </blockquote> <h3>Example of header - h3</h3> <p> Sed dignissim, neque ac malesuada eleifend, diam dolor ullamcorper nulla, et venenatis lectus justo et urna. Nulla facilisi. </p> <h4>Example of header - h4</h4> <p> Suspendisse sit amet nunc id sem ullamcorper porttitor. </p> <h5>Example of header - h5</h5> <p> Curabitur a rutrum dui. </p> <h6>Example of header - h6</h6> <p> Vestibulum eu erat id enim pellentesque gravida. </p> <h2>Lists and Floats - h2</h2> <p> Nulla mattis enim nec turpis volutpat convallis. </p> <div class="left"> <h3>Float left - h3</h3> <ul> <li>Unordered List Item 1</li> <li>Unordered List Item 2</li> <li> <h4>Unordered List Item 3 (with Children) - h4</h4> <ul> <li>Second Level Unordered List Item 1</li> <li>Second Level Unordered List Item 2</li> </ul> </li> <li> <h4>Unordered List Item 4 (with Children) - h4</h4> <ol> <li> <h5>Second Level Ordered List Item 1 - h5</h5> <p> Proin pulvinar dui a ipsum lacinia sagittis. Curabitur sed odio eu lacus volutpat hendrerit eu in justo. Etiam vitae orci nunc. Phasellus egestas auctor urna, tristique vestibulum elit consequat vel. Aliquam erat volutpat. </p> <h6>Cont. Second Level Ordered List Item 1 - h6</h6> <p> Donec lobortis purus at erat ultricies condimentum. </p> </li> <li>Second Level Ordered List Item 2</li> </ol> </li> </ul> </div> <div class="right"> <h3>Float right - h3</h3> <ol> <li>Ordered List Item 1</li> <li>Ordered List Item 2</li> <li> <h4>Ordered List Item 3 (with Children) - h4</h4> <ul> <li>Second Level Unordered List Item 1</li> <li>Second Level Unordered List Item 2</li> </ul> </li> <li> <h4>Ordered List Item 4 (with Children) - h4</h4> <ol> <li> <h5>Second Level Ordered List Item 1 - h5</h5> <p> Proin pulvinar dui a ipsum lacinia sagittis. Curabitur sed odio eu lacus volutpat hendrerit eu in justo. Etiam vitae orci nunc. Phasellus egestas auctor urna, tristique vestibulum elit consequat vel. Aliquam erat volutpat. </p> <h6>Cont. Second Level Ordered List Item 1 - h6</h6> <p> Donec lobortis purus at erat ultricies condimentum. </p> </li> <li>Second Level Ordered List Item 2</li> </ol> </li> </ol> </div> <h3>Middle content in between the floated divs. - h3</h3> <p> Suspendisse sit amet nunc id sem ullamcorper porttitor. Curabitur a rutrum dui. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aenean ipsum dolor, molestie sed ultricies eu, fermentum vitae enim. Vestibulum eu erat id enim pellentesque gravida. Mauris sed lectus velit. </p> <br class="clear" /> <h3>Content after a clear element - h3</h3> <p> Ut et lorem sit amet ante pellentesque ultrices. Sed diam arcu, dapibus non molestie a, dignissim ac sapien. Fusce sed neque augue, non sagittis massa. </p> <h2>Table Example - h2</h2> <p> Nullam at dui nunc. Vestibulum ullamcorper nisl et leo iaculis porttitor iaculis erat posuere. Proin tincidunt velit in ante lobortis in suscipit elit pharetra. </p> <table> <caption>Table Caption</caption> <thead> <tr> <th>Table Head TH</th> <th>Table Head TH</th> </tr> </thead> <tfoot> <tr> <td>Table Foot TD</td> <td>Table Foot TD</td> </tr> </tfoot> <tbody> <tr> <td>Table Body TD</td> <td>Table Body TD</td> </tr> <tr> <td>Table Body TD</td> <td>Table Body TD</td> </tr> </tbody> </table> <h2>Form Example - h2</h2> <form> <fieldset> <legend>Fieldset Legend:</legend> <div class="content-body-form-row"> <label for="lismod">File:</label> <input type="file" size="30" id="lismod" /> </div> <div class="content-body-form-row"> <label for="sceleris-lacinia">Radio1:</label> <input type="radio" name="sceleris" id="sceleris-lacinia" /> <label for="sceleris-mattis">Radio2:</label> <input type="radio" name="sceleris" id="sceleris-mattis" /> </div> <div class="content-body-form-row"> <label for="sceleris-lacerg">Textarea:</label> <textarea name="sceleris" id="sceleris-lacerg" cols="5" rows="5"> Textarea body text </textarea> </div> </fieldset> <fieldset> <legend>Fieldset Legend:</legend> <div class="content-body-form-row"> <label for="ligula">Text:</label> <input type="text" size="30" id="ligula" /> </div> <div class="content-body-form-row"> <label for="auctor">Password:</label> <input type="password" size="30" id="auctor" /> </div> <div class="content-body-form-row"> <label for="mattis">Checkbox:</label> <input type="checkbox" id="mattis" /> </div> <div class="content-body-form-row"> <label for="gestas">Select:</label> <select id="gestas"> <optgroup label="Swedish Cars"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> </optgroup> <optgroup label="German Cars"> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </optgroup> </select> </div> </fieldset> <button type="submit"><span class="hide-text">Search</span></button> </form> <h2>Iframe Example - h2</h2> <iframe src="http://www.google.com/"> <p>Your browser does not support iframes.</p> </iframe> <h2>Linked Image Example - h2</h2> <a href="#"><img src="http://www.google.ca/intl/en_com/images/srpr/logo1w.png" /></a> </div> </div> </body> </html>
During the template design phase of a website, I like to break down my work into identifiable phases. One of such phases that I go through is writing the markup for the website. I typically write the markup for the website before I write any css styles in order to come up with the most semantic xhtml possible. One last step that I take before finishing the markup and start applying styles is adding this snippet's test content to my content element. The test content in this snippet allows for testing of styles on all common xhtml tags, effectively simulating the appearance of any webpage on your site. As long as you have included styling for all of these major xhtml tags, elements on this page should appear as they do in your final product.
Stephen Chappell/Directory Pruner 1 ( python)
#! /usr/bin/env python
"""Module providing GUI capability to prune any directory.
The code presented in this module is for the purposes of: (1) ascertaining
the space taken up by a directory, its files, its sub-directories, and its
sub-files; (2) allowing for the removal of the sub-files, sub-directories,
files, and directory found in the first purpose; (3) giving the user a GUI
to accomplish said purposes in a convenient way that is easily accessible."""
################################################################################
__author__ = 'Stephen "Zero" Chappell <Noctis.Skytower@gmail.com>'
__date__ = '15 February 2011'
__version__ = '$Revision: 298 $'
################################################################################
# Import several GUI libraries.
import tkinter
import tkinter.ttk
import tkinter.filedialog
import tkinter.messagebox
# Import other needed modules.
import zlib
import base64
import os
import math
################################################################################
ICON = b'eJxjYGAEQgEBBiApwZDBzMAgxsDAoAHEQCEGBQaIOAwkQDE2UOSkiUM\
Gp/rlyd740Ugzf8/uXROxAaA4VvVAqcfYAFCcoHqge4hR/+btWwgCqoez8aj//fs\
XWiAARfCrhyCg+XA2HvV/YACoHs4mRj0ywKWe1PD//p+B4QMOmqGeMAYAAY/2nw=='
################################################################################
class GUISizeTree(tkinter.ttk.Frame):
"Widget for examining size of directory with optional deletion."
WARN = True # Should warnings be made for permanent operations?
MENU = True # Should the (destructive) context menu be enabled?
# Give names to columns.
CLMS = 'total_size', 'file_size', 'path'
TREE = '#0'
########################################################################
# Allow direct execution of GUISizeTree widget.
@classmethod
def main(cls):
"Create an application containing a single GUISizeTree widget."
tkinter.NoDefaultRoot()
root = cls.create_application_root()
cls.attach_window_icon(root, ICON)
view = cls.setup_class_instance(root)
root.mainloop()
@staticmethod
def create_application_root():
"Create and configure the main application window."
root = tkinter.Tk()
root.minsize(430, 215)
root.title('Directory Pruner')
root.option_add('*tearOff', tkinter.FALSE)
return root
@staticmethod
def attach_window_icon(root, icon):
"Generate and use the icon in the window's corner."
with open('tree.ico', 'wb') as file:
file.write(zlib.decompress(base64.b64decode(ICON)))
root.iconbitmap('tree.ico')
os.remove('tree.ico')
@classmethod
def setup_class_instance(cls, root):
"Build GUISizeTree instance that expects resizing."
instance = cls(root)
instance.grid(row=0, column=0, sticky=tkinter.NSEW)
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
return instance
########################################################################
# Initialize the GUISizeTree object.
def __init__(self, master=None, **kw):
"Initialize the GUISizeTree instance and configure for operation."
super().__init__(master, **kw)
# Initialize and configure this frame widget.
self.capture_root()
self.create_widgets()
self.create_supports()
self.create_bindings()
self.configure_grid()
self.configure_tree()
self.configure_menu()
# Set focus to path entry.
self.__path.focus_set()
def capture_root(self):
"Capture the root (Tk instance) of this application."
widget = self.master
while not isinstance(widget, tkinter.Tk):
widget = widget.master
self.__tk = widget
def create_widgets(self):
"Create all the widgets that will be placed in this frame."
self.__label = tkinter.ttk.Button(self, text='Path:',
command=self.choose)
self.__path = tkinter.ttk.Entry(self, cursor='xterm')
self.__run = tkinter.ttk.Button(self, text='Search',
command=self.search)
self.__cancel = tkinter.ttk.Button(self, text='Cancel',
command=self.stop_search)
self.__progress = tkinter.ttk.Progressbar(self,
orient=tkinter.HORIZONTAL)
self.__tree = tkinter.ttk.Treeview(self, columns=self.CLMS,
selectmode=tkinter.BROWSE)
self.__scroll_1 = tkinter.ttk.Scrollbar(self, orient=tkinter.VERTICAL,
command=self.__tree.yview)
self.__scroll_2 = tkinter.ttk.Scrollbar(self, orient=tkinter.HORIZONTAL,
command=self.__tree.xview)
self.__grip = tkinter.ttk.Sizegrip(self)
def create_supports(self):
"Create all GUI elements not placed directly in this frame."
self.__menu = tkinter.Menu(self)
self.create_directory_browser()
self.create_error_message()
self.create_warning_message()
def create_directory_browser(self):
"Find root of file system and create directory browser."
head, tail = os.getcwd(), True
while tail:
head, tail = os.path.split(head)
self.__dialog = tkinter.filedialog.Directory(self, initialdir=head)
def create_error_message(self):
"Create error message when trying to search bad path."
options = {'title': 'Path Error',
'icon': tkinter.messagebox.ERROR,
'type': tkinter.messagebox.OK,
'message': 'Directory does not exist.'}
self.__error = tkinter.messagebox.Message(self, **options)
def create_warning_message(self):
"Create warning message for permanent operations."
options = {'title': 'Important Warning',
'icon': tkinter.messagebox.QUESTION,
'type': tkinter.messagebox.YESNO,
'message': '''\
You cannot undo these operations.
Are you sure you want to do this?'''}
self.__warn = tkinter.messagebox.Message(self, **options)
def create_bindings(self):
"Bind the widgets to any events they will need to handle."
self.__label.bind('<Return>', self.choose)
self.__path.bind('<Control-Key-a>', self.select_all)
self.__path.bind('<Control-Key-/>', lambda event: 'break')
self.__path.bind('<Return>', self.search)
self.__run.bind('<Return>', self.search)
self.__cancel.bind('<Return>', self.stop_search)
self.bind_right_click(self.__tree, self.open_menu)
@staticmethod
def select_all(event):
"Select all of the contents in this Entry widget."
event.widget.selection_range(0, tkinter.END)
return 'break'
def bind_right_click(self, widget, action):
"Bind action to widget while considering Apple computers."
if self.__tk.tk.call('tk', 'windowingsystem') == 'aqua':
widget.bind('<2>', action)
widget.bind('<Control-1>', action)
else:
widget.bind('<3>', action)
def configure_grid(self):
"Place all widgets on the grid in their respective locations."
self.__label.grid(row=0, column=0)
self.__path.grid(row=0, column=1, sticky=tkinter.EW)
self.__run.grid(row=0, column=2, columnspan=2)
self.__run.grid_remove()
self.__cancel.grid(row=0, column=2, columnspan=2)
self.__cancel.grid_remove()
self.__run.grid()
self.__progress.grid(row=1, column=0, columnspan=4, sticky=tkinter.EW)
self.__tree.grid(row=2, column=0, columnspan=3, sticky=tkinter.NSEW)
self.__scroll_1.grid(row=2, column=3, sticky=tkinter.NS)
self.__scroll_2.grid(row=3, column=0, columnspan=3, sticky=tkinter.EW)
self.__grip.grid(row=3, column=3, sticky=tkinter.SE)
# Configure the grid to automatically resize internal widgets.
self.grid_rowconfigure(2, weight=1)
self.grid_columnconfigure(1, weight=1)
def configure_tree(self):
"Configure the Treeview widget."
# Setup the headings.
self.__tree.heading(self.TREE, text=' Name', anchor=tkinter.W,
command=self.sort_name)
self.__tree.heading(self.CLMS[0], text=' Total Size', anchor=tkinter.W,
command=self.sort_total_size)
self.__tree.heading(self.CLMS[1], text=' File Size', anchor=tkinter.W,
command=self.sort_file_size)
self.__tree.heading(self.CLMS[2], text=' Path', anchor=tkinter.W,
command=self.sort_path)
# Setup the columns.
self.__tree.column(self.TREE, minwidth=100, width=200)
self.__tree.column(self.CLMS[0], minwidth=100, width=200)
self.__tree.column(self.CLMS[1], minwidth=100, width=200)
self.__tree.column(self.CLMS[2], minwidth=100, width=200)
# Connect the Scrollbars.
self.__tree.configure(yscrollcommand=self.__scroll_1.set)
self.__tree.configure(xscrollcommand=self.__scroll_2.set)
def configure_menu(self):
"Configure the (context) Menu widget."
# Shortcut for narrowing the search.
self.__menu.add_command(label='Search Directory',
command=self.search_dir)
self.__menu.add_separator()
# Operations committed on directory.
self.__menu.add_command(label='Remove Directory', command=self.rm_dir)
self.__menu.add_command(label='Remove Files', command=self.rm_files)
self.__menu.add_separator()
# Operations that recurse on sub-directories.
self.__menu.add_command(label='Remove Sub-directories',
command=self.rm_subdirs)
self.__menu.add_command(label='Remove Sub-files',
command=self.rm_subfiles)
# Only add "Open Directory" command on Windows.
if hasattr(os, 'startfile'):
self.__menu.add_separator()
self.__menu.add_command(label='Open Directory',
command=self.open_dir)
########################################################################
# This property is used to control access to operations.
def __get_operations_enabled(self):
"Return if run button is in normal state."
return self.__run['state'].string == tkinter.NORMAL
def __set_operations_enabled(self, value):
"Enable or disable run button's state according to value."
self.__run['state'] = tkinter.NORMAL if value else tkinter.DISABLED
operations_enabled = property(__get_operations_enabled,
__set_operations_enabled,
doc="Flag controlling certain operations")
########################################################################
# Handle path browsing and searching actions.
def choose(self, event=None):
"Show directory browser and set path as needed."
path = self.__dialog.show()
if path:
# Entry is cleared before absolute path is added.
self.__path.delete(0, tkinter.END)
self.__path.insert(0, os.path.abspath(path))
def search(self, event=None):
"Search the path and display the size of the directory."
if self.operations_enabled:
self.operations_enabled = False
# Get absolute path and check existence.
path = os.path.abspath(self.__path.get())
if os.path.isdir(path):
# Enable operations after finishing search.
self.__search(path)
self.operations_enabled = True
else:
self.shake()
def __search(self, path):
"Execute the search procedure and display in Treeview."
self.__run.grid_remove()
self.__cancel.grid()
children = self.start_search()
try:
tree = SizeTree(self.update_search, path)
except StopIteration:
self.handle_stop_search(children)
else:
self.finish_search(children, tree)
self.__cancel.grid_remove()
self.__run.grid()
########################################################################
# Execute various phases of a search.
def start_search(self):
"Edit the GUI in preparation for executing a search."
self.__stop_search = False
children = Apply(TreeviewNode(self.__tree).children)
children.detach()
self.__progress.configure(mode='indeterminate', maximum=100)
self.__progress.start()
return children
def update_search(self):
"Check if search has been stopped and update the GUI."
self.validate_search()
self.update()
def validate_search(self):
"Check that the current search action is valid."
if self.__stop_search:
self.__stop_search = False
raise StopIteration('Search has been canceled!')
def stop_search(self, event=None):
"Cancel a search by setting its stop flag."
self.__stop_search = True
def handle_stop_search(self, children):
"Reset the Treeview and Progressbar on premature termination."
children.reattach()
self.__progress.stop()
self.__progress['mode'] = 'determinate'
def finish_search(self, children, tree):
"Delete old children, update Progressbar, and update Treeview."
children.delete()
self.__progress.stop()
self.__progress.configure(mode='determinate',
maximum=tree.total_nodes+1)
node = TreeviewNode(self.__tree).append(tree.name)
try:
self.build_tree(node, tree)
except StopIteration:
pass
########################################################################
# Handle Treeview column sorting events initiated by user.
def sort_name(self):
"Sort children of selected node by name."
TreeviewNode.current(self.__tree).sort_name()
def sort_total_size(self):
"Sort children of selected node by total size."
TreeviewNode.current(self.__tree).sort_total_size()
def sort_file_size(self):
"Sort children of selected node by file size."
TreeviewNode.current(self.__tree).sort_file_size()
def sort_path(self):
"Sort children of selected node by path."
TreeviewNode.current(self.__tree).sort_path()
########################################################################
# Handle right-click events on the Treeview widget.
def open_menu(self, event):
"Select Treeview row and show context menu if allowed."
item = event.widget.identify_row(event.y)
if item:
event.widget.selection_set(item)
if self.menu_allowed:
self.__menu.post(event.x_root, event.y_root)
@property
def menu_allowed(self):
"Check if menu is enabled along with operations."
return self.MENU and self.operations_enabled
def search_dir(self):
"Search the path of the currently selected row."
path = TreeviewNode.current(self.__tree).path
self.__path.delete(0, tkinter.END)
self.__path.insert(0, path)
self.search()
def rm_dir(self):
"Remove the currently selected directory."
if self.commit_permanent_operation:
self.do_remove_directory()
def rm_files(self):
"Remove the files in the currently selected directory."
if self.commit_permanent_operation:
self.do_remove_files()
def rm_subdirs(self):
"Remove the sub-directories of the currently selected directory."
if self.commit_permanent_operation:
self.do_remove_subdirectories()
def rm_subfiles(self):
"Remove the sub-files of the currently selected directory."
if self.commit_permanent_operation:
self.do_remove_subfiles()
@property
def commit_permanent_operation(self):
"Check if warning should be issued before committing operation."
return not self.WARN or self.__warn.show() == tkinter.messagebox.YES
def open_dir(self):
"Open up the current directory (only available on Windows)."
os.startfile(TreeviewNode.current(self.__tree).path)
########################################################################
# Execute actions requested by context menu.
def do_remove_directory(self):
"Remove a directory and all of its sub-directories."
self.begin_rm()
# Get the current Treeview node and delete it.
node = TreeviewNode.current(self.__tree)
directory_size, path = node.total_size, node.path
position, parent = node.position, node.delete(True)
# Delete the entire directory at path.
self.__rm_dir(self.update, path, True, True)
if os.path.isdir(path):
# Add the directory back to the Treeview.
tree = SizeTree(self.update, path)
self.begin_rm_update(tree.total_nodes + 1)
# Rebuild the Treeview under the parent.
node = parent.insert(position, tree.name)
self.build_tree(node, tree)
# New directory size.
total_size = tree.total_size
else:
self.begin_rm_update()
# New directory size.
total_size = 0
# If the size has changed, update parent nodes.
if directory_size != total_size:
diff = total_size - directory_size
self.update_parents(parent, diff)
self.end_rm()
def do_remove_files(self):
"Remove all of the files in the selected directory."
# Delete files in the directory and get its new size.
node = TreeviewNode.current(self.__tree)
total_size = self.__rm_files(node.path)
# Update current and parent nodes if the size changed.
if node.file_size != total_size:
diff = total_size - node.file_size
node.file_size = total_size
node.total_size += diff
self.update_parents(node.parent, diff)
def do_remove_subdirectories(self):
"Remove all subdirectories in the directory."
self.begin_rm()
# Remove all the children nodes in Viewtree.
node = TreeviewNode.current(self.__tree)
for child in node.children:
child.delete()
# Delete all of the subdirectories and their files.
self.__rm_dir(self.update, node.path, True)
# Find out what subdirectories could not be deteled.
tree = SizeTree(self.update, node.path)
self.begin_rm_update(tree.total_nodes)
if tree.total_nodes:
# Rebuild the Viewtree as needed.
self.build_tree(node, tree, False)
# Fix node and prepare to update parents.
diff = node.total_size - tree.total_size
node.total_size = tree.total_size
else:
# Fix node and prepare to update parents.
diff = node.file_size - node.total_size
node.total_size = node.file_size
# Update parents with new size.
self.update_parents(node.parent, diff)
self.end_rm()
def do_remove_subfiles(self):
"Remove all subfiles while keeping subdirectories in place."
self.begin_rm()
# Delete all subfiles from current directory.
node = TreeviewNode.current(self.__tree)
self.__rm_dir(self.update, node.path)
# Build a new SizeTree to find the result.
tree = SizeTree(self.update, node.path)
self.begin_rm_update(tree.total_nodes)
# Record the difference and patch the Viewtree.
diff = tree.total_size - node.total_size
self.patch_tree(node, tree)
# Fix all parent nodes with the correct size.
self.update_parents(node.parent, diff)
self.end_rm()
########################################################################
# Help update Progressbar in removal process.
def begin_rm(self):
"Start a long-running removal operation."
self.operations_enabled = False
self.__progress.configure(mode='indeterminate', maximum=100)
self.__progress.start()
def begin_rm_update(self, nodes=0):
"Move to determinate mode of updating the Viewtree."
self.__progress.stop()
self.__progress.configure(mode='determinate', maximum=nodes)
def end_rm(self):
"Finish removal process by enabling operations."
self.operations_enabled = True
########################################################################
# Help in removing directories and files.
@staticmethod
def __rm_dir(callback, path, rm_dir=False, rm_root=False):
"Remove directory at path, respecting the flags."
for root, dirs, files in os.walk(path, False):
# Ignore path if rm_root is false.
if rm_root or root != path:
callback()
for name in files:
file_name = os.path.join(root, name)
# Remove file while catching errors.
try:
os.remove(file_name)
except OSError:
pass
# Ignore directory if rm_dir is false.
if rm_dir:
try:
os.rmdir(root)
except OSError:
pass
@staticmethod
def __rm_files(path):
"Remove files in path and get remaining space."
total_size = 0
# Find all files in directory of path.
for name in os.listdir(path):
path_name = os.path.join(path, name)
if os.path.isfile(path_name):
# Try to remove any file that may have been found.
try:
os.remove(path_name)
except OSError:
try:
# If there was an error, try to get the filesize.
total_size += os.path.getsize(path_name)
except OSError:
pass
# Return best guess of space still occupied.
return total_size
########################################################################
# Update the Viewtree nodes after creating a SizeTree object.
def build_tree(self, node, tree, update_node=True):
"Build the Treeview while updating the Progressbar."
self.validate_search()
if update_node:
self.sync_nodes(node, tree)
self.add_children(node, tree)
def sync_nodes(self, node, tree):
"Update attributes on node and refresh GUI."
# Copy the information on the node.
node.total_size = tree.total_size
node.file_size = tree.file_size
node.path = tree.path
# Update the Progressbar and GUI.
self.__progress.step()
self.update()
def patch_tree(self, node, tree):
"Patch differences between node and tree."
node.total_size = tree.total_size
node.file_size = tree.file_size
self.patch_children(node, tree)
self.add_children(node, tree)
def add_children(self, node, tree):
"Build and traverse all child nodes."
for child in tree.children:
subnode = node.append(child.name)
self.build_tree(subnode, child)
def patch_children(self, node, tree):
"Patch Viewtree based on children of SizeTree."
for subnode in node.children:
child = tree.pop_child(subnode.name)
if child is None:
# Directory is gone.
subnode.delete()
else:
# Dig down further in tree.
self.__progress.step()
self.update()
self.patch_tree(subnode, child)
@staticmethod
def update_parents(node, diff):
"Add in difference to node and parents."
while not node.root:
node.total_size += diff
node = node.parent
########################################################################
# Show an error when searching paths that do not exist.
def shake(self, force=False):
"Prepare to shake the application's root window."
if force:
tkinter._tkinter.setbusywaitinterval(20)
elif tkinter._tkinter.getbusywaitinterval() != 20:
# Show error message if not running at 50 FPS.
self.__error.show()
self.operations_enabled = True
return
# Shake window at 50 FPS.
self.after_idle(self.__shake)
def __shake(self, frame=0):
"Animate each step of shaking the root window."
frame += 1
# Get the window's location and update the X position.
x, y = map(int, self.__tk.geometry().split('+')[1:])
x += round(math.sin(math.pi * frame / 2.5) * \
math.sin(math.pi * frame / 50) * 5)
self.__tk.geometry('+{}+{}'.format(x, y))
if frame < 50:
# Schedule next step in the animation.
self.after(20, self.__shake, frame)
else:
# Enable operations after one second.
self.operations_enabled = True
################################################################################
class TreeviewNode:
"Interface to allow easier interaction with Treeview instance."
@classmethod
def current(cls, tree):
"Take a tree view and return its currently selected node."
node = tree.selection()
return cls(tree, node[0] if node else node)
########################################################################
# Standard Treeview Operations
__slots__ = '__tree', '__node'
def __init__(self, tree, node=''):
"Initialize the TreeviewNode object (root if node not given)."
self.__tree = tree
self.__node = node
def __str__(self):
"Return a string representation of this node."
return '''\
NODE: {!r}
Name: {}
Total Size: {}
File Size: {}
Path {}\
'''.format(self.__node, self.name, self.total_size, self.file_size, self.path)
def insert(self, position, text):
"Insert a new node with text at position in current node."
node = self.__tree.insert(self.__node, position, text=text)
return TreeviewNode(self.__tree, node)
def append(self, text):
"Add a new node with text to the end of this node."
return self.insert(tkinter.END, text)
def move(self, parent, index):
"Insert this node under parent at index."
self.__tree.move(self.__node, parent, index)
def reattach(self, parent='', index=tkinter.END):
"Attach node to parent at index (defaults to end of root)."
self.move(parent, index)
def detach(self):
"Unlink this node from its parent but do not delete."
self.__tree.detach(self.__node)
def delete(self, get_parent=False):
"Delete this node (optionally, return parent)."
if self.__tree.exists(self.__node):
parent = self.parent if get_parent else None
self.__tree.delete(self.__node)
return parent
assert not get_parent, 'Cannot return parent!'
########################################################################
# Standard Treeview Properties
@property
def root(self):
"Return if this is the root node."
return self.__node == ''
@property
def parent(self):
"Return the parent of this node."
return TreeviewNode(self.__tree, self.__tree.parent(self.__node))
@property
def level(self):
"Return number of levels this node is under root."
count, node = 0, self
while not node.root:
node = node.parent
count += 1
return count
@property
def position(self):
"Return the position of this node in its parent."
return self.__tree.index(self.__node)
@property
def expanded(self):
"Return whether or not the node is current open."
value = self.__tree.item(self.__node, 'open')
return bool(value) and value.string == 'true'
@property
def children(self):
"Yield back each child of this node."
for child in self.__tree.get_children(self.__node):
yield TreeviewNode(self.__tree, child)
########################################################################
# Custom Treeview Properties
# (specific for application)
@property
def name(self):
"Return the name of this node (tree column)."
return self.__tree.item(self.__node, 'text')
def __get_total_size(self):
return parse(self.__tree.set(self.__node, GUISizeTree.CLMS[0]))
def __set_total_size(self, value):
self.__tree.set(self.__node, GUISizeTree.CLMS[0], convert(value))
total_size = property(__get_total_size, __set_total_size,
doc="Total size of this node (first column)")
def __get_file_size(self):
return parse(self.__tree.set(self.__node, GUISizeTree.CLMS[1]))
def __set_file_size(self, value):
self.__tree.set(self.__node, GUISizeTree.CLMS[1], convert(value))
file_size = property(__get_file_size, __set_file_size,
doc="File size of this node (second column)")
def __get_path(self):
return self.__tree.set(self.__node, GUISizeTree.CLMS[2])
def __set_path(self, value):
self.__tree.set(self.__node, GUISizeTree.CLMS[2], value)
path = property(__get_path, __set_path,
doc="Path of this node (third column)")
########################################################################
# Custom Treeview Sort Order
# (specific for application)
def sort_name(self):
"If the node is open, sort its children by name."
self.__sort(lambda child: child.name)
def sort_total_size(self):
"If the node is open, sort its children by total size."
self.__sort(lambda child: child.total_size)
def sort_file_size(self):
"If the node is open, sort its children by file size."
self.__sort(lambda child: child.file_size)
def sort_path(self):
"If the node is open, sort its children by path."
self.__sort(lambda child: child.path)
def __sort(self, key):
"Sort an expanded node's children by the given key."
if self.expanded:
nodes = list(self.children)
order = sorted(nodes, key=key)
if order == nodes:
order = reversed(order)
for child in order:
self.__tree.move(child.__node, self.__node, tkinter.END)
################################################################################
class SizeTree:
"Create a tree structure outlining a directory's size."
__slots__ = 'name path children file_size total_size total_nodes'.split()
def __init__(self, callback, path):
"Initialize the SizeTree object and search the path while updating."
callback() # Allow the GUI to be updated.
head, tail = os.path.split(path)
# Create attributes for this instance.
self.name = tail or head
self.path = path
self.children = []
self.file_size = 0
self.total_size = 0
self.total_nodes = 0
# Try searching this directory.
try:
dir_list = os.listdir(path)
except OSError:
pass
else:
# Examine each object in this directory.
for name in dir_list:
path_name = os.path.join(path, name)
if os.path.isdir(path_name):
# Create child nodes for subdirectories.
size_tree = SizeTree(callback, path_name)
self.children.append(size_tree)
self.total_size += size_tree.total_size
self.total_nodes += size_tree.total_nodes + 1
elif os.path.isfile(path_name):
# Try getting the size of files.
try:
self.file_size += os.path.getsize(path_name)
except OSError:
pass
# Add in the total file size to the total size.
self.total_size += self.file_size
def pop_child(self, name):
"Return a named child or None if not found."
for index, child in enumerate(self.children):
if child.name == name:
return self.children.pop(index)
########################################################################
def __str__(self):
"Return a representation of the tree formed by this object."
lines = [self.path]
self.__walk(lines, self.children, '')
return '\n'.join(lines)
@classmethod
def __walk(cls, lines, children, prefix):
"Generate lines based on children and keep track of prefix."
dir_prefix, walk_prefix = prefix + '+---', prefix + '| '
for pos, neg, child in cls.__enumerate(children):
if neg == -1:
dir_prefix, walk_prefix = prefix + '\\---', prefix + ' '
lines.append(dir_prefix + child.name)
cls.__walk(lines, child.children, walk_prefix)
@staticmethod
def __enumerate(sequence):
"Generate positive and negative indices for sequence."
length = len(sequence)
for count, value in enumerate(sequence):
yield count, count - length, value
################################################################################
class Apply(tuple):
"Create a container that can run a method from its contents."
def __getattr__(self, name):
"Get a virtual method to map and apply to the contents."
return self.__Method(self, name)
########################################################################
class __Method:
"Provide a virtual method that can be called on the array."
def __init__(self, array, name):
"Initialize the method with array and method name."
self.__array = array
self.__name = name
def __call__(self, *args, **kwargs):
"Execute method on contents with provided arguments."
name, error, buffer = self.__name, False, []
for item in self.__array:
attr = getattr(item, name)
try:
data = attr(*args, **kwargs)
except Exception as problem:
error = problem
else:
if not error:
buffer.append(data)
if error:
raise error
return tuple(buffer)
################################################################################
# Provide a way of converting byte sizes into strings.
def convert(number):
"Convert bytes into human-readable representation."
if not number:
return '0 Bytes'
assert 0 < number < 1 << 110, 'number out of range'
ordered = reversed(tuple(format_bytes(partition_number(number, 1 << 10))))
cleaned = ', '.join(item for item in ordered if item[0] != '0')
return cleaned
def partition_number(number, base):
"Continually divide number by base until zero."
div, mod = divmod(number, base)
yield mod
while div:
div, mod = divmod(div, base)
yield mod
def format_bytes(parts):
"Format partitioned bytes into human-readable strings."
for power, number in enumerate(parts):
yield '{} {}'.format(number, format_suffix(power, number))
def format_suffix(power, number):
"Compute the suffix for a certain power of bytes."
return (PREFIX[power] + 'byte').capitalize() + ('s' if number != 1 else '')
PREFIX = ' kilo mega giga tera peta exa zetta yotta bronto geop'.split(' ')
################################################################################
# Allow conversion of byte size strings back into numbers.
def parse(string):
"Convert human-readable string back into bytes."
total = 0
for part in string.split(', '):
number, unit = part.split(' ')
s = number != '1' and 's' or ''
for power, prefix in enumerate(PREFIX):
if unit == (prefix + 'byte' + s).capitalize():
break
else:
raise ValueError('{!r} not found!'.format(unit))
total += int(number) * 1 << 10 * power
return total
################################################################################
# Execute the main method if ran directly.
if __name__ == '__main__':
GUISizeTree.main()
This program is an extension of recipe 577567 in that it not only allows one to find a directory's size but also remove files based on a context menu. The directory pruner has been used by my roommate to free up room on his hard drive and also by several friends that wished to remove games and other unnecessary program that were taking up their space. Right-click on found directories to review your options.
If you wish to vote this recipe down, please post a comment at the bottom telling me how you would improve the utility.
Stephen Chappell/Directory Pruner 2 ( python)
#! /usr/bin/env python
"""Module providing GUI capability to prune any directory.
The code presented in this module is for the purposes of: (1) ascertaining
the space taken up by a directory, its files, its sub-directories, and its
sub-files; (2) allowing for the removal of the sub-files, sub-directories,
files, and directory found in the first purpose; (3) giving the user a GUI
to accomplish said purposes in a convenient way that is easily accessible."""
################################################################################
__author__ = 'Stephen "Zero" Chappell <Noctis.Skytower@gmail.com>'
__date__ = '21 February 2011'
__version__ = '$Revision: 417 $'
################################################################################
# Import several GUI libraries.
import tkinter.filedialog
import tkinter.messagebox
import tkinter.ttk
# Import other needed modules.
import _thread
import base64
import functools
import logging
import math
import operator
import os
import queue
import sys
import time
import traceback
import warnings
import zlib
################################################################################
ICON = b'eJxjYGAEQgEBBiApwZDBzMAgxsDAoAHEQCEGBQaIOAwkQDE2UOSkiUM\
Gp/rlyd740Ugzf8/uXROxAaA4VvVAqcfYAFCcoHqge4hR/+btWwgCqoez8aj//fs\
XWiAARfCrhyCg+XA2HvV/YACoHs4mRj0ywKWe1PD//p+B4QMOmqGeMAYAAY/2nw=='
################################################################################
class Affinity:
"Predecessor to AffinityLoop that might not return results."
__slots__ = '__action', '__thread'
def __init__(self):
"Initialize Affinity with job queue and thread identity."
self.__action = queue.Queue()
self.__thread = _thread.get_ident()
def run(self, func, *args, **keywords):
"Try to run function with arguments on the creating thread."
self.__action.put_nowait(functools.partial(func, *args, **keywords))
if _thread.get_ident() == self.__thread:
problem = False
while not self.__action.empty():
delegate = self.__action.get_nowait()
try:
data = delegate()
except Exception as error:
problem = error
if problem:
raise problem
return data
warnings.warn('Affinity did not return!')
################################################################################
class AffinityLoop:
"Restricts code execution to thread that instance was created on."
__slots__ = '__action', '__thread'
def __init__(self):
"Initialize AffinityLoop with job queue and thread identity."
self.__action = queue.Queue()
self.__thread = _thread.get_ident()
def run(self, func, *args, **keywords):
"Run function on creating thread and return result."
if _thread.get_ident() == self.__thread:
self.__run_jobs()
return func(*args, **keywords)
else:
job = self.__Job(func, args, keywords)
self.__action.put_nowait(job)
return job.result
def __run_jobs(self):
"Run all pending jobs currently in the job queue."
while not self.__action.empty():
job = self.__action.get_nowait()
job.execute()
########################################################################
class __Job:
"Store information to run a job at a later time."
__slots__ = ('__func', '__args', '__keywords',
'__error', '__mutex', '__value')
def __init__(self, func, args, keywords):
"Initialize the job's info and ready for execution."
self.__func = func
self.__args = args
self.__keywords = keywords
self.__error = False
self.__mutex = _thread.allocate_lock()
self.__mutex.acquire()
def execute(self):
"Run the job, store any error, and return to sender."
try:
self.__value = self.__func(*self.__args, **self.__keywords)
except Exception as error:
self.__error = True
self.__value = error
self.__mutex.release()
@property
def result(self):
"Return execution result or raise an error."
self.__mutex.acquire()
if self.__error:
raise self.__value
return self.__value
################################################################################
class _ThreadSafe:
"Create a thread-safe GUI class for safe cross-threaded calls."
ROOT = tkinter.Tk
def __init__(self, master=None, *args, **keywords):
"Initialize a thread-safe wrapper around a GUI base class."
if master is None:
if self.BASE is not self.ROOT:
raise ValueError('Widget must have a master!')
self.__job = AffinityLoop() # Use Affinity() if it does not break.
self.__schedule(self.__initialize, *args, **keywords)
else:
self.master = master
self.__job = master.__job
self.__schedule(self.__initialize, master, *args, **keywords)
def __initialize(self, *args, **keywords):
"Delegate instance creation to later time if necessary."
self.__obj = self.BASE(*args, **keywords)
########################################################################
# Provide a framework for delaying method execution when needed.
def __schedule(self, *args, **keywords):
"Schedule execution of a method till later if necessary."
return self.__job.run(self.__run, *args, **keywords)
@classmethod
def __run(cls, func, *args, **keywords):
"Execute the function after converting the arguments."
args = tuple(cls.unwrap(i) for i in args)
keywords = dict((k, cls.unwrap(v)) for k, v in keywords.items())
return func(*args, **keywords)
@staticmethod
def unwrap(obj):
"Unpack inner objects wrapped by _ThreadSafe instances."
return obj.__obj if isinstance(obj, _ThreadSafe) else obj
########################################################################
# Allow access to and manipulation of wrapped instance's settings.
def __getitem__(self, key):
"Get a configuration option from the underlying object."
return self.__schedule(operator.getitem, self, key)
def __setitem__(self, key, value):
"Set a configuration option on the underlying object."
return self.__schedule(operator.setitem, self, key, value)
########################################################################
# Create attribute proxies for methods and allow their execution.
def __getattr__(self, name):
"Create a requested attribute and return cached result."
attr = self.__Attr(self.__callback, (name,))
setattr(self, name, attr)
return attr
def __callback(self, path, *args, **keywords):
"Schedule execution of named method from attribute proxy."
return self.__schedule(self.__method, path, *args, **keywords)
def __method(self, path, *args, **keywords):
"Extract a method and run it with the provided arguments."
method = self.__obj
for name in path:
method = getattr(method, name)
return method(*args, **keywords)
########################################################################
class __Attr:
"Save an attribute's name and wait for execution."
__slots__ = '__callback', '__path'
def __init__(self, callback, path):
"Initialize proxy with callback and method path."
self.__callback = callback
self.__path = path
def __call__(self, *args, **keywords):
"Run a known method with the given arguments."
return self.__callback(self.__path, *args, **keywords)
def __getattr__(self, name):
"Generate a proxy object for a sub-attribute."
if name in {'__func__', '__name__'}:
# Hack for the "tkinter.__init__.Misc._register" method.
raise AttributeError('This is not a real method!')
return self.__class__(self.__callback, self.__path + (name,))
################################################################################
# Provide thread-safe classes to be used from tkinter.
class Tk(_ThreadSafe): BASE = tkinter.Tk
class Frame(_ThreadSafe): BASE = tkinter.ttk.Frame
class Button(_ThreadSafe): BASE = tkinter.ttk.Button
class Entry(_ThreadSafe): BASE = tkinter.ttk.Entry
class Progressbar(_ThreadSafe): BASE = tkinter.ttk.Progressbar
class Treeview(_ThreadSafe): BASE = tkinter.ttk.Treeview
class Scrollbar(_ThreadSafe): BASE = tkinter.ttk.Scrollbar
class Sizegrip(_ThreadSafe): BASE = tkinter.ttk.Sizegrip
class Menu(_ThreadSafe): BASE = tkinter.Menu
class Directory(_ThreadSafe): BASE = tkinter.filedialog.Directory
class Message(_ThreadSafe): BASE = tkinter.messagebox.Message
################################################################################
# Allow starting threads that can be debugged.
def start_thread(function, *args, **kwargs):
"Start a new thread and wrap with error catching."
_thread.start_new_thread(_bootstrap, (function, args, kwargs))
def _bootstrap(function, args, kwargs):
"Run function with arguments and log any errors."
try:
function(*args, **kwargs)
except Exception:
basename = os.path.basename(sys.argv[0])
filename = os.path.splitext(basename)[0] + '.log'
logging.basicConfig(filename=filename)
logging.error(traceback.format_exc())
################################################################################
class TrimDirView(Frame):
"Widget for examining size of directory with optional deletion."
WARN = True # Should warnings be made for permanent operations?
MENU = True # Should the (destructive) context menu be enabled?
SIZE = True # Should directory sizes be patched for less words?
# Give names to columns.
CLMS = 'total_size', 'file_size', 'path'
TREE = '#0'
########################################################################
# Allow direct execution of TrimDirView widget.
@classmethod
def main(cls):
"Create an application containing a single TrimDirView widget."
tkinter.NoDefaultRoot()
root = cls.create_application_root()
cls.attach_window_icon(root, ICON)
view = cls.setup_class_instance(root)
cls.main_loop(root)
@staticmethod
def create_application_root():
"Create and configure the main application window."
root = Tk()
root.minsize(430, 215)
root.title('Directory Pruner')
root.option_add('*tearOff', tkinter.FALSE)
return root
@staticmethod
def attach_window_icon(root, icon):
"Generate and use the icon in the window's corner."
with open('tree.ico', 'wb') as file:
file.write(zlib.decompress(base64.b64decode(ICON)))
root.iconbitmap('tree.ico')
os.remove('tree.ico')
@classmethod
def setup_class_instance(cls, root):
"Build TrimDirView instance that expects resizing."
instance = cls(root)
instance.grid(row=0, column=0, sticky=tkinter.NSEW)
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
return instance
@staticmethod
def main_loop(root):
"Process all GUI events according to tkinter's settings."
target = time.clock()
while True:
try:
root.update()
except tkinter.TclError:
break
target += tkinter._tkinter.getbusywaitinterval() / 1000
time.sleep(max(target - time.clock(), 0))
########################################################################
# Initialize the TrimDirView object.
__slots__ = ('__tk', '__label', '__path', '__run', '__cancel',
'__progress', '__tree', '__scroll_1', '__scroll_2',
'__grip', '__menu', '__dialog', '__error', '__warn')
def __init__(self, master=None, **kw):
"Initialize the TrimDirView instance and configure for operation."
super().__init__(master, **kw)
# Initialize and configure this frame widget.
self.capture_root()
self.create_widgets()
self.create_supports()
self.create_bindings()
self.configure_grid()
self.configure_tree()
self.configure_menu()
# Set focus to path entry.
self.__path.focus_set()
def capture_root(self):
"Capture the root (Tk instance) of this application."
widget = self.master
while not isinstance(widget, Tk):
widget = widget.master
self.__tk = widget
def create_widgets(self):
"Create all the widgets that will be placed in this frame."
self.__label = Button(self, text='Path:', command=self.choose)
self.__path = Entry(self, cursor='xterm')
self.__run = Button(self, text='Search', command=self.search)
self.__cancel = Button(self, text='Cancel', command=self.stop_search)
self.__progress = Progressbar(self, orient=tkinter.HORIZONTAL)
self.__tree = Treeview(self, columns=self.CLMS,
selectmode=tkinter.BROWSE)
self.__scroll_1 = Scrollbar(self, orient=tkinter.VERTICAL,
command=self.__tree.yview)
self.__scroll_2 = Scrollbar(self, orient=tkinter.HORIZONTAL,
command=self.__tree.xview)
self.__grip = Sizegrip(self)
def create_supports(self):
"Create all GUI elements not placed directly in this frame."
self.__menu = Menu(self)
self.create_directory_browser()
self.create_error_message()
self.create_warning_message()
def create_directory_browser(self):
"Find root of file system and create directory browser."
head, tail = os.getcwd(), True
while tail:
head, tail = os.path.split(head)
self.__dialog = Directory(self, initialdir=head)
def create_error_message(self):
"Create error message when trying to search bad path."
options = {'title': 'Path Error',
'icon': tkinter.messagebox.ERROR,
'type': tkinter.messagebox.OK,
'message': 'Directory does not exist.'}
self.__error = Message(self, **options)
def create_warning_message(self):
"Create warning message for permanent operations."
options = {'title': 'Important Warning',
'icon': tkinter.messagebox.QUESTION,
'type': tkinter.messagebox.YESNO,
'message': '''\
You cannot undo these operations.
Are you sure you want to do this?'''}
self.__warn = Message(self, **options)
def create_bindings(self):
"Bind the widgets to any events they will need to handle."
self.__label.bind('<Return>', self.choose)
self.__path.bind('<Control-Key-a>', self.select_all)
self.__path.bind('<Control-Key-/>', lambda event: 'break')
self.__path.bind('<Return>', self.search)
self.__run.bind('<Return>', self.search)
self.__cancel.bind('<Return>', self.stop_search)
self.bind_right_click(self.__tree, self.open_menu)
@staticmethod
def select_all(event):
"Select all of the contents in this Entry widget."
event.widget.selection_range(0, tkinter.END)
return 'break'
def bind_right_click(self, widget, action):
"Bind action to widget while considering Apple computers."
if self.__tk.tk.call('tk', 'windowingsystem') == 'aqua':
widget.bind('<2>', action)
widget.bind('<Control-1>', action)
else:
widget.bind('<3>', action)
def configure_grid(self):
"Place all widgets on the grid in their respective locations."
self.__label.grid(row=0, column=0)
self.__path.grid(row=0, column=1, sticky=tkinter.EW)
self.__run.grid(row=0, column=2, columnspan=2)
self.__run.grid_remove()
self.__cancel.grid(row=0, column=2, columnspan=2)
self.__cancel.grid_remove()
self.__run.grid()
self.__progress.grid(row=1, column=0, columnspan=4, sticky=tkinter.EW)
self.__tree.grid(row=2, column=0, columnspan=3, sticky=tkinter.NSEW)
self.__scroll_1.grid(row=2, column=3, sticky=tkinter.NS)
self.__scroll_2.grid(row=3, column=0, columnspan=3, sticky=tkinter.EW)
self.__grip.grid(row=3, column=3, sticky=tkinter.SE)
# Configure the grid to automatically resize internal widgets.
self.grid_rowconfigure(2, weight=1)
self.grid_columnconfigure(1, weight=1)
def configure_tree(self):
"Configure the Treeview widget."
# Setup the headings.
self.__tree.heading(self.TREE, text=' Name', anchor=tkinter.W,
command=self.sort_name)
self.__tree.heading(self.CLMS[0], text=' Total Size', anchor=tkinter.W,
command=self.sort_total_size)
self.__tree.heading(self.CLMS[1], text=' File Size', anchor=tkinter.W,
command=self.sort_file_size)
self.__tree.heading(self.CLMS[2], text=' Path', anchor=tkinter.W,
command=self.sort_path)
# Setup the columns.
self.__tree.column(self.TREE, minwidth=100, width=200)
self.__tree.column(self.CLMS[0], minwidth=100, width=200)
self.__tree.column(self.CLMS[1], minwidth=100, width=200)
self.__tree.column(self.CLMS[2], minwidth=100, width=200)
# Connect the Scrollbars.
self.__tree.configure(yscrollcommand=self.__scroll_1.set)
self.__tree.configure(xscrollcommand=self.__scroll_2.set)
# PATCH: Provide data store.
if TrimDirView.SIZE:
self.__tree.nodes = dict()
def configure_menu(self):
"Configure the (context) Menu widget."
# Shortcut for narrowing the search.
self.__menu.add_command(label='Search Directory',
command=self.search_dir)
self.__menu.add_separator()
# Operations committed on directory.
self.__menu.add_command(label='Remove Directory', command=self.rm_dir)
self.__menu.add_command(label='Remove Files', command=self.rm_files)
self.__menu.add_separator()
# Operations that recurse on sub-directories.
self.__menu.add_command(label='Remove Sub-directories',
command=self.rm_subdirs)
self.__menu.add_command(label='Remove Sub-files',
command=self.rm_subfiles)
self.__menu.add_separator()
# Operations that remove empty directories and files.
self.__menu.add_command(label='Remove Empty Directories',
command=self.rm_empty_dirs)
self.__menu.add_command(label='Remove Empty Files',
command=self.rm_empty_files)
# Only add "Open Directory" command on Windows.
if hasattr(os, 'startfile'):
self.__menu.add_separator()
self.__menu.add_command(label='Open Directory',
command=self.open_dir)
########################################################################
# This property is used to control access to operations.
def __get_operations_enabled(self):
"Return if run button is in normal state."
return self.__run['state'].string == tkinter.NORMAL
def __set_operations_enabled(self, value):
"Enable or disable run button's state according to value."
self.__run['state'] = tkinter.NORMAL if value else tkinter.DISABLED
operations_enabled = property(__get_operations_enabled,
__set_operations_enabled,
doc="Flag controlling certain operations")
########################################################################
# Handle path browsing and searching actions.
def choose(self, event=None):
"Show directory browser and set path as needed."
path = self.__dialog.show()
if path:
# Entry is cleared before absolute path is added.
self.__path.delete(0, tkinter.END)
self.__path.insert(0, os.path.abspath(path))
def search(self, event=None):
"Start search thread while GUI automatically updates."
start_thread(self.search_thread)
def search_thread(self):
"Search the path and display the size of the directory."
if self.operations_enabled:
self.operations_enabled = False
# Get absolute path and check existence.
path = os.path.abspath(self.__path.get())
if os.path.isdir(path):
# Enable operations after finishing search.
self.__search(path)
self.operations_enabled = True
else:
indicate_error(self.__tk, self.__error, self.enable_operations)
def __search(self, path):
"Execute the search procedure and display in Treeview."
self.__run.grid_remove()
self.__cancel.grid()
children = self.start_search()
try:
tree = SizeTree(path, self.validate_search)
except StopIteration:
self.handle_stop_search(children)
else:
self.finish_search(children, tree)
self.__cancel.grid_remove()
self.__run.grid()
########################################################################
# Execute various phases of a search.
def start_search(self):
"Edit the GUI in preparation for executing a search."
self.__stop_search = False
children = Apply(TreeviewNode(self.__tree).children)
children.detach()
self.__progress.configure(mode='indeterminate', maximum=100)
self.__progress.start()
return children
def validate_search(self):
"Check that the current search action is valid."
if self.__stop_search:
self.__stop_search = False
raise StopIteration('Search has been canceled!')
def stop_search(self, event=None):
"Cancel a search by setting its stop flag."
self.__stop_search = True
def handle_stop_search(self, children):
"Reset the Treeview and Progressbar on premature termination."
children.reattach()
self.__progress.stop()
self.__progress['mode'] = 'determinate'
def finish_search(self, children, tree):
"Delete old children, update Progressbar, and update Treeview."
children.delete()
self.__progress.stop()
self.__progress.configure(mode='determinate',
maximum=tree.total_nodes+1)
node = TreeviewNode(self.__tree).append(tree.name)
try:
self.build_tree(node, tree)
except StopIteration:
pass
########################################################################
# Handle Treeview column sorting events initiated by user.
def sort_name(self):
"Sort children of selected node by name."
TreeviewNode.current(self.__tree).sort_name()
def sort_total_size(self):
"Sort children of selected node by total size."
TreeviewNode.current(self.__tree).sort_total_size()
def sort_file_size(self):
"Sort children of selected node by file size."
TreeviewNode.current(self.__tree).sort_file_size()
def sort_path(self):
"Sort children of selected node by path."
TreeviewNode.current(self.__tree).sort_path()
########################################################################
# Handle right-click events on the Treeview widget.
def open_menu(self, event):
"Select Treeview row and show context menu if allowed."
item = event.widget.identify_row(event.y)
if item:
event.widget.selection_set(item)
if self.menu_allowed:
self.__menu.post(event.x_root, event.y_root)
@property
def menu_allowed(self):
"Check if menu is enabled along with operations."
return self.MENU and self.operations_enabled
def search_dir(self):
"Search the path of the currently selected row."
path = TreeviewNode.current(self.__tree).path
self.__path.delete(0, tkinter.END)
self.__path.insert(0, path)
self.search()
def rm_dir(self):
"Remove the currently selected directory."
if self.commit_permanent_operation:
start_thread(self.do_remove_directory)
def rm_files(self):
"Remove the files in the currently selected directory."
if self.commit_permanent_operation:
start_thread(self.do_remove_files)
def rm_subdirs(self):
"Remove the sub-directories of the currently selected directory."
if self.commit_permanent_operation:
start_thread(self.do_remove_subdirectories)
def rm_subfiles(self):
"Remove the sub-files of the currently selected directory."
if self.commit_permanent_operation:
start_thread(self.do_remove_subfiles)
def rm_empty_dirs(self):
"Recursively remove empty directories from selected directory."
if self.commit_permanent_operation:
start_thread(self.do_remove_empty_dirs)
def rm_empty_files(self):
"Recursively remove empty files from selected directory."
if self.commit_permanent_operation:
start_thread(self.do_remove_empty_files)
@property
def commit_permanent_operation(self):
"Check if warning should be issued before committing operation."
return not self.WARN or self.__warn.show() == tkinter.messagebox.YES
def open_dir(self):
"Open up the current directory (only available on Windows)."
os.startfile(TreeviewNode.current(self.__tree).path)
########################################################################
# Execute actions requested by context menu.
def do_remove_directory(self):
"Remove a directory and all of its sub-directories."
self.begin_rm()
# Get the current Treeview node and delete it.
node = TreeviewNode.current(self.__tree)
directory_size, path = node.total_size, node.path
position, parent = node.position, node.delete(True)
# Delete the entire directory at path.
remove_directory_files(path, True, True)
if os.path.isdir(path):
# Add the directory back to the Treeview.
tree = SizeTree(path)
self.begin_rm_update(tree.total_nodes + 1)
# Rebuild the Treeview under the parent.
node = parent.insert(position, tree.name)
self.build_tree(node, tree)
# New directory size.
total_size = tree.total_size
else:
self.begin_rm_update()
# New directory size.
total_size = 0
# If the size has changed, update parent nodes.
if directory_size != total_size:
diff = total_size - directory_size
self.update_parents(parent, diff)
self.end_rm()
def do_remove_files(self):
"Remove all of the files in the selected directory."
# Delete files in the directory and get its new size.
node = TreeviewNode.current(self.__tree)
total_size = remove_files(node.path)
# Update current and parent nodes if the size changed.
if node.file_size != total_size:
diff = total_size - node.file_size
node.file_size = total_size
node.total_size += diff
self.update_parents(node.parent, diff)
def do_remove_subdirectories(self):
"Remove all subdirectories in the directory."
self.begin_rm()
# Remove all the children nodes in Viewtree.
node = TreeviewNode.current(self.__tree)
for child in node.children:
child.delete()
# Delete all of the subdirectories and their files.
remove_directory_files(node.path, True)
# Find out what subdirectories could not be deteled.
tree = SizeTree(node.path)
self.begin_rm_update(tree.total_nodes)
if tree.total_nodes:
# Rebuild the Viewtree as needed.
self.build_tree(node, tree, False)
# Fix node and prepare to update parents.
diff = node.total_size - tree.total_size
node.total_size = tree.total_size
else:
# Fix node and prepare to update parents.
diff = node.file_size - node.total_size
node.total_size = node.file_size
# Update parents with new size.
self.update_parents(node.parent, diff)
self.end_rm()
def do_remove_subfiles(self):
"Remove all subfiles while keeping subdirectories in place."
self.begin_rm()
node = TreeviewNode.current(self.__tree)
remove_directory_files(node.path)
self.synchronize_tree(node)
def do_remove_empty_dirs(self):
"Remove all empty directories from selected directory."
self.begin_rm()
node = TreeviewNode.current(self.__tree)
remove_empty_directories(node.path)
self.synchronize_tree(node)
def do_remove_empty_files(self):
"Remove all empty files from selected directory."
self.begin_rm()
# Remove empty files from the current path.
node = TreeviewNode.current(self.__tree)
remove_empty_files(node.path)
# Return the Progressbar back to normal.
self.begin_rm_update()
self.end_rm()
########################################################################
# Help update Progressbar in removal process.
def begin_rm(self):
"Start a long-running removal operation."
self.operations_enabled = False
self.__progress.configure(mode='indeterminate', maximum=100)
self.__progress.start()
def begin_rm_update(self, nodes=0):
"Move to determinate mode of updating the Viewtree."
self.__progress.stop()
self.__progress.configure(mode='determinate', maximum=nodes)
def end_rm(self):
"Finish removal process by enabling operations."
self.operations_enabled = True
enable_operations = end_rm # Create alias for command.
########################################################################
# Update the Viewtree nodes after creating a SizeTree object.
def synchronize_tree(self, node):
"Find the current directory state and update the tree."
# Build a new SizeTree to find the result.
tree = SizeTree(node.path)
self.begin_rm_update(tree.total_nodes)
# Record the difference and patch the Viewtree.
diff = tree.total_size - node.total_size
self.patch_tree(node, tree)
# Fix all parent nodes with the correct size.
self.update_parents(node.parent, diff)
self.end_rm()
def build_tree(self, node, tree, update_node=True):
"Build the Treeview while updating the Progressbar."
self.validate_search()
if update_node:
self.sync_nodes(node, tree)
self.add_children(node, tree)
def sync_nodes(self, node, tree):
"Update attributes on node and refresh GUI."
# Copy the information on the node.
node.total_size = tree.total_size
node.file_size = tree.file_size
node.path = tree.path
# Update the Progressbar and GUI.
self.__progress.step()
def patch_tree(self, node, tree):
"Patch differences between node and tree."
node.total_size = tree.total_size
node.file_size = tree.file_size
self.patch_children(node, tree)
self.add_children(node, tree)
def add_children(self, node, tree):
"Build and traverse all child nodes."
for child in tree.children:
subnode = node.append(child.name)
self.build_tree(subnode, child)
def patch_children(self, node, tree):
"Patch Viewtree based on children of SizeTree."
for subnode in node.children:
child = tree.pop_child(subnode.name)
if child is None:
# Directory is gone.
subnode.delete()
else:
# Dig down further in tree.
self.__progress.step()
self.patch_tree(subnode, child)
@staticmethod
def update_parents(node, diff):
"Add in difference to node and parents."
while not node.root:
node.total_size += diff
node = node.parent
################################################################################
# Show an error when searching paths that do not exist.
def indicate_error(root, alternative, callback, force=False):
"Prepare to shake the application's root window."
if force:
tkinter._tkinter.setbusywaitinterval(20)
elif tkinter._tkinter.getbusywaitinterval() != 20:
# Show error message if not running at 50 FPS.
alternative.show()
return callback()
root.after_idle(_shake, root, callback)
def _shake(root, callback, frame=0):
"Animate each step of shaking the root window."
frame += 1
# Get the window's location and update the X position.
x, y = map(int, root.geometry().split('+')[1:])
x += round(math.sin(math.pi * frame / 2.5) * \
math.sin(math.pi * frame / 50) * 5)
root.geometry('+{}+{}'.format(x, y))
if frame < 50:
# Schedule next step in the animation.
root.after(20, _shake, root, callback, frame)
else:
# Enable operations after one second.
callback()
################################################################################
# Help in removing directories and files with these functions.
def remove_directory_files(path, remove_directory=False, remove_path=False):
"Remove directory at path, respecting the flags."
for root, dirs, files in os.walk(path, False):
# Ignore path if remove_path is false.
if remove_path or root != path:
for name in files:
filename = os.path.join(root, name)
try:
os.remove(filename)
except OSError:
pass
# Ignore directory if remove_directory is false.
if remove_directory:
try:
os.rmdir(root)
except OSError:
pass
def remove_files(path):
"Remove files in path and get remaining space."
total_size = 0
# Find all files in directory of path.
for name in os.listdir(path):
pathname = os.path.join(path, name)
if os.path.isfile(pathname):
# Try to remove any file that may have been found.
try:
os.remove(pathname)
except OSError:
# If there was an error, try to get the filesize.
try:
total_size += os.path.getsize(pathname)
except OSError:
pass
# Return best guess of space still occupied.
return total_size
def remove_empty_directories(path, remove_root=False, recursive=True):
"Remove all empty directories while respecting the flags."
if recursive:
for name in os.listdir(path):
try:
remove_empty_directories(os.path.join(path, name), True)
except OSError:
pass
if remove_root:
os.rmdir(path)
def remove_empty_files(path, recursive=True):
"Remove all files that are empty of any contents."
for root, dirs, files in os.walk(path):
if not recursive:
del dirs[:]
for name in files:
filename = os.path.join(root, name)
try:
if not os.path.getsize(filename):
os.remove(filename)
except OSError:
pass
################################################################################
class TreeviewNode:
"Interface to allow easier interaction with Treeview instance."
@classmethod
def current(cls, tree):
"Take a tree view and return its currently selected node."
node = tree.selection()
return cls(tree, node[0] if node else node)
########################################################################
# Standard Treeview Operations
__slots__ = '__tree', '__node'
def __init__(self, tree, node=''):
"Initialize the TreeviewNode object (root if node not given)."
self.__tree = tree
self.__node = node
def __str__(self):
"Return a string representation of this node."
return '''\
NODE: {!r}
Name: {}
Total Size: {}
File Size: {}
Path {}\
'''.format(self.__node, self.name, self.total_size, self.file_size, self.path)
def insert(self, position, text):
"Insert a new node with text at position in current node."
node = self.__tree.insert(self.__node, position, text=text)
# PATCH: Store extra data about node.
if TrimDirView.SIZE:
self.__tree.nodes[node] = dict()
return TreeviewNode(self.__tree, node)
def append(self, text):
"Add a new node with text to the end of this node."
return self.insert(tkinter.END, text)
def move(self, parent, index):
"Insert this node under parent at index."
self.__tree.move(self.__node, parent, index)
def reattach(self, parent='', index=tkinter.END):
"Attach node to parent at index (defaults to end of root)."
self.move(parent, index)
def detach(self):
"Unlink this node from its parent but do not delete."
self.__tree.detach(self.__node)
def delete(self, get_parent=False, from_tree=True): # Internal Last Flag
"Delete this node (optionally, return parent)."
if self.__tree.exists(self.__node):
parent = self.parent if get_parent else None
# PATCH: Remove extra data about node.
if TrimDirView.SIZE:
for child in self.children:
child.delete(from_tree=False)
del self.__tree.nodes[self.__node]
if from_tree:
self.__tree.delete(self.__node)
#=====================================
return parent
if get_parent:
raise ValueError('Cannot return parent!')
########################################################################
# Standard Treeview Properties
@property
def root(self):
"Return if this is the root node."
return self.__node == ''
@property
def parent(self):
"Return the parent of this node."
return TreeviewNode(self.__tree, self.__tree.parent(self.__node))
@property
def level(self):
"Return number of levels this node is under root."
count, node = 0, self
while not node.root:
node = node.parent
count += 1
return count
@property
def position(self):
"Return the position of this node in its parent."
return self.__tree.index(self.__node)
@property
def expanded(self):
"Return whether or not the node is current open."
value = self.__tree.item(self.__node, 'open')
return bool(value) and value.string == 'true'
@property
def children(self):
"Yield back each child of this node."
for child in self.__tree.get_children(self.__node):
yield TreeviewNode(self.__tree, child)
########################################################################
# Custom Treeview Properties
# (specific for application)
@property
def name(self):
"Return the name of this node (tree column)."
return self.__tree.item(self.__node, 'text')
# PATCH: Custom Size
if TrimDirView.SIZE:
# Shortened Byte Size
def __get_total_size(self):
return self.__tree.nodes[self.__node][TrimDirView.CLMS[0]]
def __set_total_size(self, value):
self.__tree.nodes[self.__node][TrimDirView.CLMS[0]] = value
self.__tree.set(self.__node, TrimDirView.CLMS[0], abbr(value))
def __get_file_size(self):
return self.__tree.nodes[self.__node][TrimDirView.CLMS[1]]
def __set_file_size(self, value):
self.__tree.nodes[self.__node][TrimDirView.CLMS[1]] = value
self.__tree.set(self.__node, TrimDirView.CLMS[1], abbr(value))
else:
# Complete Byte Size
def __get_total_size(self):
return parse(self.__tree.set(self.__node, TrimDirView.CLMS[0]))
def __set_total_size(self, value):
self.__tree.set(self.__node, TrimDirView.CLMS[0], convert(value))
def __get_file_size(self):
return parse(self.__tree.set(self.__node, TrimDirView.CLMS[1]))
def __set_file_size(self, value):
self.__tree.set(self.__node, TrimDirView.CLMS[1], convert(value))
#========================================================================
def __get_path(self):
return self.__tree.set(self.__node, TrimDirView.CLMS[2])
def __set_path(self, value):
self.__tree.set(self.__node, TrimDirView.CLMS[2], value)
total_size = property(__get_total_size, __set_total_size,
doc="Total size of this node (first column)")
file_size = property(__get_file_size, __set_file_size,
doc="File size of this node (second column)")
path = property(__get_path, __set_path,
doc="Path of this node (third column)")
########################################################################
# Custom Treeview Sort Order
# (specific for application)
def sort_name(self):
"If the node is open, sort its children by name."
self.__sort(lambda child: child.name)
def sort_total_size(self):
"If the node is open, sort its children by total size."
self.__sort(lambda child: child.total_size)
def sort_file_size(self):
"If the node is open, sort its children by file size."
self.__sort(lambda child: child.file_size)
def sort_path(self):
"If the node is open, sort its children by path."
self.__sort(lambda child: child.path)
def __sort(self, key):
"Sort an expanded node's children by the given key."
if self.expanded:
nodes = list(self.children)
order = sorted(nodes, key=key)
if order == nodes:
order = reversed(order)
for child in order:
self.__tree.move(child.__node, self.__node, tkinter.END)
################################################################################
class SizeTree:
"Create a tree structure outlining a directory's size."
__slots__ = 'name path children file_size total_size total_nodes'.split()
def __init__(self, path, callback=None):
"Initialize the SizeTree object and search the path while updating."
# Validate the search's current progress.
if callback is not None:
callback()
head, tail = os.path.split(path)
# Create attributes for this instance.
self.name = tail or head
self.path = path
self.children = []
self.file_size = 0
self.total_size = 0
self.total_nodes = 0
# Try searching this directory.
try:
dir_list = os.listdir(path)
except OSError:
pass
else:
# Examine each object in this directory.
for name in dir_list:
path_name = os.path.join(path, name)
if os.path.isdir(path_name):
# Create child nodes for subdirectories.
size_tree = SizeTree(path_name, callback)
self.children.append(size_tree)
self.total_size += size_tree.total_size
self.total_nodes += size_tree.total_nodes + 1
elif os.path.isfile(path_name):
# Try getting the size of files.
try:
self.file_size += os.path.getsize(path_name)
except OSError:
pass
# Add in the total file size to the total size.
self.total_size += self.file_size
def pop_child(self, name):
"Return a named child or None if not found."
for index, child in enumerate(self.children):
if child.name == name:
return self.children.pop(index)
########################################################################
def __str__(self):
"Return a representation of the tree formed by this object."
lines = [self.path]
self.__walk(lines, self.children, '')
return '\n'.join(lines)
@classmethod
def __walk(cls, lines, children, prefix):
"Generate lines based on children and keep track of prefix."
dir_prefix, walk_prefix = prefix + '+---', prefix + '| '
for pos, neg, child in cls.__enumerate(children):
if neg == -1:
dir_prefix, walk_prefix = prefix + '\\---', prefix + ' '
lines.append(dir_prefix + child.name)
cls.__walk(lines, child.children, walk_prefix)
@staticmethod
def __enumerate(sequence):
"Generate positive and negative indices for sequence."
length = len(sequence)
for count, value in enumerate(sequence):
yield count, count - length, value
################################################################################
class Apply(tuple):
"Create a container that can run a method from its contents."
def __getattr__(self, name):
"Get a virtual method to map and apply to the contents."
return self.__Method(self, name)
########################################################################
class __Method:
"Provide a virtual method that can be called on the array."
def __init__(self, array, name):
"Initialize the method with array and method name."
self.__array = array
self.__name = name
def __call__(self, *args, **kwargs):
"Execute method on contents with provided arguments."
name, error, buffer = self.__name, False, []
for item in self.__array:
attr = getattr(item, name)
try:
data = attr(*args, **kwargs)
except Exception as problem:
error = problem
else:
if not error:
buffer.append(data)
if error:
raise error
return tuple(buffer)
################################################################################
# Provide a way of converting byte sizes into strings.
def convert(number):
"Convert bytes into human-readable representation."
if not number:
return '0 Bytes'
if not 0 < number < 1 << 110:
raise ValueError('Number out of range!')
ordered = reversed(tuple(format_bytes(partition_number(number, 1 << 10))))
cleaned = ', '.join(item for item in ordered if item[0] != '0')
return cleaned
def partition_number(number, base):
"Continually divide number by base until zero."
div, mod = divmod(number, base)
yield mod
while div:
div, mod = divmod(div, base)
yield mod
def format_bytes(parts):
"Format partitioned bytes into human-readable strings."
for power, number in enumerate(parts):
yield '{} {}'.format(number, format_suffix(power, number))
def format_suffix(power, number):
"Compute the suffix for a certain power of bytes."
return (PREFIX[power] + 'byte').capitalize() + ('s' if number != 1 else '')
PREFIX = ' kilo mega giga tera peta exa zetta yotta bronto geop'.split(' ')
################################################################################
# Define additional operations for the TreeviewNode class.
def parse(string):
"Convert human-readable string back into bytes."
total = 0
for part in string.split(', '):
number, unit = part.split(' ')
s = number != '1' and 's' or ''
for power, prefix in enumerate(PREFIX):
if unit == (prefix + 'byte' + s).capitalize():
break
else:
raise ValueError('{!r} not found!'.format(unit))
total += int(number) * 1 << 10 * power
return total
def abbr(number):
"Convert bytes into abbreviated representation."
# Check value of number before processing.
if not number:
return '0 Bytes'
if not 0 < number < (1 << 100) * 1000:
raise ValueError('Number out of range!')
# Calculate range of number and correct value.
level = int(math.log(number) / math.log(1 << 10))
value = number / (1 << 10 * level)
# Move to the next level if number is high enough.
if value < 1000:
precision = 4
else:
precision = 3
level += 1
value /= 1 << 10
# Format the number before returning to caller.
if level:
result = '{:.{}}'.format(value, precision)
return '{} {}'.format(result, format_suffix(level, result == '1.0'))
return '{} {}'.format(int(value), format_suffix(level, value))
################################################################################
# Execute main method if ran directly.
if __name__ == '__main__':
TrimDirView.main()
This program builds on work done in recipe 577632, adds new options to the context menu, and experiments with threading the GUI. Directory Pruner 2 appear to work better on Windows 7 while Directory Pruner 1 (the non-threaded version) performs better on Windows XP. Those are the primary platforms on which the two programs have been tested. Please use these applications at your own risk.
If you do not like something about this recipe and want to vote it down, please let everyone what you find fault with, how you would improve it, and an example of the code you would improve.
Macgeeky/slett alt i Nedlastinger (Applescript) ( AppleScript)
tell application "Finder" set mappen to the folder "Mac HD:Users:Robert:Downloads" set filtrert to (files of mappen where label index is not 4) delete filtrert end tell
Just a simple script that deletes everything in the Downloads folder, except for files that is labeled with the blue label in Finder (Color label this script blue, as a program in the Downloads folder, and click it to delete all the other files in Downloads).\r\n\r\n1. Save script as Program in the Downloads folder\r\n2. Label the program with the blue color label in Finder\r\n3. Everytime you would like to delete everything in the Downloads folder -> click this program (in Downloads stack in the Dock).\r\n\r\nPS! Remember to change \\'Robert\\' to your Mac OS username! \\"Robert\\" in line 2.
brano sobotka/Classic ASP script analyzer, finds all functions, includes, duplicite functions ( python)
""" Classic ASP script analyzer, finds all functions, includes, duplicate functions """
#TO-DO: testing, it was tested only on one big project
import string, re, sys, os.path, logging, sqlite3
from Tkinter import *
import tkFileDialog, tkMessageBox
def find_functions(file_name, data, db_cursor, functions):
""" finds all functions in asp script """
my_re = re.compile(r'[^\'\"][ ]{0,10}function[ ]{1,3}(?P<fun>[a-z0-9_\-]{1,30})', re.IGNORECASE)
res = my_re.findall(data)
if res:
for line in res:
print "function", line.lower()
tmp = file_name + '\t\t' + line.lower() #(file_name, line)
functions.append(tmp)
db_cursor.execute("""insert into project_functions
values ((SELECT max(id) FROM project_functions)+1, '%s', '%s', 'function')""" % (file_name, line.lower()))
my_re = re.compile(r'[^\'\"][ ]{0,10}sub[ ]{1,3}(?P<fun>[a-z0-9_\-]{1,30})', re.IGNORECASE)
res = my_re.findall(data)
if res:
for line in res:
print "sub", line.lower()
#tmp = (file_name, line)
tmp = file_name + '\t\t' + line.lower() #(file_name, line)
functions.append(tmp)
db_cursor.execute("""insert into project_functions
values ((SELECT max(id) FROM project_functions)+1, '%s', '%s', 'sub')""" % (file_name, line.lower()))
def find_includes(file_path, recursive_level, dir_before, db_cursor, includes, functions):
""" find al includes, recursive call """
for dr in dir_before:
os.chdir(dr)
try: f = open(file_path, "r")
except: pass
try:
data = f.read()
f.close()
except:
print dir_before
print file_path
return ([], [])
find_functions(os.path.split(file_path)[1], data, db_cursor, functions)
if len(os.path.split(file_path)[0]) > 1:
#print "dir_before 1", os.path.split(file_path)[0]
try:
os.chdir(os.path.split(file_path)[0]) #change work dir to script home dir
if not os.getcwd() in dir_before:
dir_before.append(os.getcwd())
except:
pass
# print "Current directory", os.getcwd(), dir_before, recursive_level
include_file = []
my_re = re.compile(r'[^\'][\s]{0,5}<!--[\s]{0,5}#[\s]{0,5}INCLUDE[\s]{0,5}FILE[\s]{0,5}=(?P<file>[ \d\w\.\\\\/_\-"]{1,50})-->', re.IGNORECASE)
res = my_re.findall(data)
if not res:
#print "No include in %s file Regexp not matched" % (file_path)
#logger.info("No include in %s file Regexp not matched" % (file_path))
return 1
else:
for line in res:
include_file.append(line.replace("\"","").strip())
#print include_file
#include_file.sort()
#include_file.reverse()
includes.append("Includes in: " + os.path.split(file_path)[0] + "\\" + os.path.split(file_path)[1])
print "Includes in:", os.path.split(file_path)[0] + "\\" + os.path.split(file_path)[1]
for inc_file in include_file:
includes.append(inc_file)
print inc_file
for inc_file in include_file:
find_includes(inc_file, recursive_level + 1, dir_before, db_cursor, includes, functions)
return (includes, functions)
def main(file_path, db_path):
""" read arguments and analyze """
if not os.path.exists(file_path):
print "File %s not found" % (file_path )
return 1
c = ''
conn = sqlite3.connect(db_path)
c = conn.cursor()
try:
c.execute('''DROP TABLE project_functions''')
except:
pass
c.execute('''create table project_functions
(id INTEGER PRIMARY KEY, script_name text, fun_name text, fun_type text)''')
includes = []
functions = []
file_path_dir = os.path.split(file_path)[0]
os.chdir(file_path_dir) #change work dir to script home dir
print file_path_dir
includes, functions = \
find_includes(file_path, 0, [file_path_dir], c, includes, functions)
conn.commit()
doubles_fun = []
c.execute("""SELECT fun_name FROM project_functions
group by fun_name
having count(fun_name) > 1""")
for fun_name in c:
doubles_fun.append(fun_name)
duplicites = []
for i,fun_name in enumerate(doubles_fun):
dup = fun_name[0] + '\t'
print i,fun_name[0]
#t = (fun_name,)
c.execute("select script_name, fun_name, fun_type from project_functions where fun_name='%s'" % (fun_name))
for row in c:
print '\t', row[0]
dup = dup + row[0] + ','
duplicites.append(dup)
c.close()
return (includes, functions, duplicites)
class App:
""" GUI """
def __init__(self, master):
self.master = master
Label(master, text="File to analyze:").grid(row=0)
Label(master, text="File for database:").grid(row=1)
#Label(master, text="File for export (optional):").grid(row=2)
self.e1 = Entry(master, width = 35)
self.e2 = Entry(master, width = 35)
self.e2.insert(INSERT, "C:\\analyze_webscript.db3")
#self.e3 = Entry(master, width = 35)
#self.e3.insert(INSERT, "X:\\temp.web\\analyze_webscript.txt")
self.e1.grid(row=0, column=1)
self.e2.grid(row=1, column=1)
#self.e3.grid(row=2, column=1)
self.b1 = Button(master, text="Browse", command=self.br1, width = 10)
self.b2 = Button(master, text="Browse", command=self.br2, width = 10)
#self.b3 = Button(master, text="Browse", command=self.br3, width = 10)
self.b1.grid(row=0, column=2)
self.b2.grid(row=1, column=2)
#self.b3.grid(row=2, column=2)
self.v1 = IntVar()
self.c1 = Checkbutton(master, text="find all includes", variable=self.v1)
self.c1.var = self.v1
self.c1.grid(columnspan=2, sticky=W)
self.v2 = IntVar()
self.c2 = Checkbutton(master, text="find all functions in all includes", variable=self.v2)
self.c2.var = self.v2
self.c2.grid(columnspan=2, sticky=W)
self.v3 = IntVar()
self.c3 = Checkbutton(master, text="find duplicite functions", variable=self.v3)
self.c3.var = self.v3
self.c3.grid(columnspan=2, sticky=W)
#self.listbox = Listbox(master, selectmode=SINGLE)
#for item in ["one", "two", "three", "four"]:
# self.listbox.insert(END, item)
#self.listbox.grid(row=3,column=1)
self.b4 = Button(master, text="Start Analyze", command = self.start_analyze, width = 15)
self.b4.grid(row=5, column=2)
self.text = Text(master,width=70, height=30)
self.vscroll = Scrollbar(master,orient=VERTICAL)
self.vscroll.grid(row=6, column=4, sticky=N+S)
self.vscroll.config(command=self.text.yview)
#self.vscroll.config(command=self.text.yview)
#self.text.config(yscrollcommand=self.vscroll.set)
self.text.grid(row=6, columnspan=3, sticky=W)
def start_analyze(self):
print "started"
print self.v1.get()
print self.v2.get()
print self.v3.get()
if (not self.v1.get()) and (not self.v2.get()) and (not self.v3.get()):
tkMessageBox.showwarning("Action", "Please choose action")
return 1
analyze_file = self.e1.get()
db_file = self.e2.get()
if len(analyze_file) == 0 or len(db_file) == 0:
tkMessageBox.showwarning("Action", "Please set file location")
return 1
print analyze_file
print db_file
#print self.e3.get()
includes, functions, duplicites = \
main(analyze_file, db_file)
#self.frame = Frame(width=768, height=576, bg="", colormap="new")
#self.ef1 = Text(self.frame, width = 50, heigth = 50)
#self.ef1.insert(INSERT, includes)
#self.frame.pack()
self.text.delete(1.0, END)
if self.v1.get():
self.text.insert(END, 'INCLUDES:\n')
self.text.insert(END, '\n'.join(includes))
if self.v2.get():
if self.v1.get():
self.text.insert(END, '\n\n')
self.text.insert(END, 'FUNCTIONS:\n')
self.text.insert(END, '\n'.join(functions))
if self.v3.get():
if self.v1.get() or self.v2.get():
self.text.insert(END, '\n\n')
self.text.insert(END, 'DUPLICATES:\n')
self.text.insert(END, '\n'.join(duplicites))
#self.text.pack(side=LEFT,expand=1,fill=BOTH)
#self.vscroll = Scrollbar(frame2,orient=VERTICAL)
#self.vscroll.pack(side=LEFT,fill=Y,anchor=E)
#self.vscroll.config(command=self.text.yview)
#self.text.config(yscrollcommand=self.vscroll.set)
#frame2.pack(expand=1,fill=BOTH)
def br1(self):
self.e1.delete(0, len(self.e1.get()))
p = tkFileDialog.askopenfilename(title = "File for analyze", initialdir = "C:\\inetpub\\wwwroot")
self.e1.insert(INSERT, p)
def br2(self):
self.e2.delete(0, len(self.e2.get()))
p = tkFileDialog.askopenfilename(title = "File for database")
self.e2.insert(INSERT, p)
#def br3(self):
# p = tkFileDialog.askopenfilename(title = "File for export")
# self.e3.insert(INSERT, p)
root = Tk()
root.title("ASP script analyzer")
App(root)
root.mainloop()
Input root of your asp project to "File to analyze" it means some default.asp or index.asp. Select what do you what to find and click start analyze. Classic ASP don't care about duplicate function names, what creates unpredictable mistakes.
bitsculptor/Custom post type, taxonomy, and messages ( PHP)
// The register_post_type() function is not to be used before the 'init'.
add_action( 'init', 'my_custom_init' );
/* Here's how to create your customized labels */
function my_custom_init() {
$labels = array(
'name' => _x( 'Portfolio Galleries', 'post type general name' ), // Tip: _x('') is used for localization
'singular_name' => _x( 'Portfolio Gallery', 'post type singular name' ),
'add_new' => _x( 'Add New', 'Portfolio Gallery' ),
'add_new_item' => __( 'Add New Portfolio Gallery' ),
'edit_item' => __( 'Edit Portfolio Gallery' ),
'new_item' => __( 'New Portfolio Gallery' ),
'view_item' => __( 'View Portfolio Gallery' ),
'search_items' => __( 'Search Portfolio Galleries' ),
'not_found' => __( 'No Portfolio Galleries found' ),
'not_found_in_trash' => __( 'No Portfolio Galleries found in Trash' ),
'parent_item_colon' => ''
);
// Create an array for the $args
$args = array( 'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'rewrite' => true,
'capability_type' => 'post',
'hierarchical' => true,
'menu_position' => null,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'page-attributes' )
);
register_post_type( 'portfolio-gallery', $args ); /* Register it and move on */
}
//add a custom message to the post message function
add_filter('post_updated_messages', 'gallery_updated_messages');
function gallery_updated_messages( $messages ) {
$messages['portfolio-gallery'] = array(
0 => '', // Unused. Messages start at index 1.
1 => sprintf( __('Gallery updated. <a href="%s">View Gallery</a>'), esc_url( get_permalink($post_ID) ) ),
2 => __('Custom field updated.'),
3 => __('Custom field deleted.'),
4 => __('Gallery updated.'),
/* translators: %s: date and time of the revision */
5 => isset($_GET['revision']) ? sprintf( __('Gallery restored to revision from %s'), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
6 => sprintf( __('Gallery published. <a href="%s">View Gallery</a>'), esc_url( get_permalink($post_ID) ) ),
7 => __('Gallery saved.'),
8 => sprintf( __('Gallery submitted. <a target="_blank" href="%s">Preview Gallery</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
9 => sprintf( __('Gallery scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview Gallery</a>'),
// translators: Publish box date format, see http://php.net/date
date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( get_permalink($post_ID) ) ),
10 => sprintf( __('Gallery draft updated. <a target="_blank" href="%s">Preview Gallery</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
);
return $messages;
}
// hook into the init action and call create_gallery_taxonomies() when it fires
add_action( 'init', 'create_gallery_taxonomies', 0 );
function create_gallery_taxonomies() {
// Add new taxonomy, hierarchical
$labels = array(
'name' => _x( 'Categories', 'taxonomy general name' ),
'singular_name' => _x( 'Category', 'taxonomy singular name' ),
'search_items' => __( 'Search Categories' ),
'popular_items' => __( 'Popular Categories' ),
'all_items' => __( 'All Categories' ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Edit Category' ),
'update_item' => __( 'Update Category' ),
'add_new_item' => __( 'Add New Category' ),
'new_item_name' => __( 'New Category Name' ),
'separate_items_with_commas' => __( 'Separate categories with commas' ),
'add_or_remove_items' => __( 'Add or remove categories' ),
'choose_from_most_used' => __( 'Choose from the most used categories' )
);
register_taxonomy( 'gallery-category', 'portfolio-gallery', array(
'hierarchical' => true,
'labels' => $labels, /* NOTICE: the $labels variable here */
'show_ui' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'gallery-category' ),
));
}
This gives the code for creating a custom post type with all the necessary labels and even custom message support, and it gives the code for a custom taxonomy with that post type.