def connectionMade(self):
dst = path.abspath(path.join(self.destDir,self.filename))
exists = path.exists(dst)
if self.resume and exists:
# I have been told I want to resume, and a file already
# exists - Here we go
self.file = open(dst, 'ab')
log.msg("Attempting to resume %s - starting from %d bytes" %
(self.file, self.file.tell()))
elif self.overwrite or not exists:
self.file = open(dst, 'wb')
else:
raise OSError(errno.EEXIST,
"There's a file in the way. "
"Perhaps that's why you cannot open it.",
dst)
python类join()的实例源码
def find_library_file (self, dirs, lib, debug=0):
# Prefer a debugging library if found (and requested), but deal
# with it if we don't have one.
if debug:
try_names = [lib + "_d", lib]
else:
try_names = [lib]
for dir in dirs:
for name in try_names:
libfile = os.path.join(dir, self.library_filename (name))
if os.path.exists(libfile):
return libfile
else:
# Oops, didn't find it in *any* of 'dirs'
return None
# find_library_file ()
# Helper methods for using the MSVC registry settings
def find_exe(self, exe):
"""Return path to an MSVC executable program.
Tries to find the program in several places: first, one of the
MSVC program search paths from the registry; next, the directories
in the PATH environment variable. If any of those work, return an
absolute path that is known to exist. If none of them work, just
return the original program name, 'exe'.
"""
for p in self.__paths:
fn = os.path.join(os.path.abspath(p), exe)
if os.path.isfile(fn):
return fn
# didn't find it; try existing path
for p in string.split(os.environ['Path'],';'):
fn = os.path.join(os.path.abspath(p),exe)
if os.path.isfile(fn):
return fn
return exe
def prune_file_list(self):
"""Prune off branches that might slip into the file list as created
by 'read_template()', but really don't belong there:
* the build tree (typically "build")
* the release tree itself (only an issue if we ran "sdist"
previously with --keep-temp, or it aborted)
* any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories
"""
build = self.get_finalized_command('build')
base_dir = self.distribution.get_fullname()
self.filelist.exclude_pattern(None, prefix=build.build_base)
self.filelist.exclude_pattern(None, prefix=base_dir)
# pruning out vcs directories
# both separators are used under win32
if sys.platform == 'win32':
seps = r'/|\\'
else:
seps = '/'
vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr',
'_darcs']
vcs_ptrn = r'(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps)
self.filelist.exclude_pattern(vcs_ptrn, is_regex=1)
def formatargspec(args, varargs=None, varkw=None, defaults=None,
formatarg=str,
formatvarargs=lambda name: '*' + name,
formatvarkw=lambda name: '**' + name,
formatvalue=lambda value: '=' + repr(value),
join=joinseq):
"""Format an argument spec from the 4 values returned by getargspec.
The first four arguments are (args, varargs, varkw, defaults). The
other four arguments are the corresponding optional formatting functions
that are called to turn names and values into strings. The ninth
argument is an optional function to format the sequence of arguments."""
specs = []
if defaults:
firstdefault = len(args) - len(defaults)
for i, arg in enumerate(args):
spec = strseq(arg, formatarg, join)
if defaults and i >= firstdefault:
spec = spec + formatvalue(defaults[i - firstdefault])
specs.append(spec)
if varargs is not None:
specs.append(formatvarargs(varargs))
if varkw is not None:
specs.append(formatvarkw(varkw))
return '(' + string.join(specs, ', ') + ')'
def formatargvalues(args, varargs, varkw, locals,
formatarg=str,
formatvarargs=lambda name: '*' + name,
formatvarkw=lambda name: '**' + name,
formatvalue=lambda value: '=' + repr(value),
join=joinseq):
"""Format an argument spec from the 4 values returned by getargvalues.
The first four arguments are (args, varargs, varkw, locals). The
next four arguments are the corresponding optional formatting functions
that are called to turn names and values into strings. The ninth
argument is an optional function to format the sequence of arguments."""
def convert(name, locals=locals,
formatarg=formatarg, formatvalue=formatvalue):
return formatarg(name) + formatvalue(locals[name])
specs = []
for i in range(len(args)):
specs.append(strseq(args[i], convert, join))
if varargs:
specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
if varkw:
specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
return '(' + string.join(specs, ', ') + ')'
def locate(path, forceload=0):
"""Locate an object by name or dotted path, importing as necessary."""
parts = [part for part in split(path, '.') if part]
module, n = None, 0
while n < len(parts):
nextmodule = safeimport(join(parts[:n+1], '.'), forceload)
if nextmodule: module, n = nextmodule, n + 1
else: break
if module:
object = module
for part in parts[n:]:
try: object = getattr(object, part)
except AttributeError: return None
return object
else:
if hasattr(__builtin__, path):
return getattr(__builtin__, path)
# --------------------------------------- interactive interpreter interface
def _norm_version(version, build=''):
""" Normalize the version and build strings and return a single
version string using the format major.minor.build (or patchlevel).
"""
l = string.split(version,'.')
if build:
l.append(build)
try:
ints = map(int,l)
except ValueError:
strings = l
else:
strings = map(str,ints)
version = string.join(strings[:3],'.')
return version
def loadConfig(self, config):
configFile = config.getConfigFile()
if not isfile(configFile):
self.logger.warn("Config file %s does not exist. Using defaults." % configFile)
return config
self.logger.debug("Loading config from %s." % configFile)
loader = ConfigParser.SafeConfigParser(allow_no_value=True)
loader.add_section("main")
loader.set("main", "log_file", config.logFile)
loader.set("main", "migration_dirs", join(config.migrationDirs, ":"))
loader.set("main", "pre_migration_dirs", join(config.preMigrationDirs, ":"))
loader.set("main", "post_migration_dirs", join(config.postMigrationDirs, ":"))
loader.set("main", "state_dir", config.stateDir)
loader.set("main", "run_dir", config.runDir)
loader.read(configFile)
config.logFile = loader.get("main", "log_file")
config.migrationDirs = split(loader.get("main", "migration_dirs"), ":")
config.preMigrationDirs = split(loader.get("main", "pre_migration_dirs"), ":")
config.postMigrationDirs = split(loader.get("main", "post_migration_dirs"), ":")
config.stateDir = loader.get("main", "state_dir")
config.runDir = loader.get("main", "run_dir")
return config
def send_email(subject, text, to_addr_list=DEFAULT_EMAIL_LIST):
body = string.join(('From: %s' % SENDING_ADDRESS,
'To: %s' % to_addr_list,
'Subject: %s' % subject,
'',
text), '\r\n')
try:
server = smtplib.SMTP('smtp.gmail.com:587') # NOTE: This is the GMAIL SSL port.
server.ehlo() # this line was not required in a previous working version
server.starttls()
server.login(SENDING_ADDRESS, 'gmail_password')
server.sendmail(SENDING_ADDRESS, to_addr_list, body)
server.quit()
print "Email sent successfully!"
except:
return "Email failed to send!"
def safe_str(o):
"""safe_str(anything) -> string
Returns a string representation of an object, or a string containing a
traceback, if that object's __str__ raised an exception.
"""
try:
return str(o)
except:
strExc = '\n'.join(traceback.format_exception(*sys.exc_info()))
clsName = _determineClassName(o)
obId = id(o)
return '<%s instance at %s with str error %s>' % (
clsName, obId, strExc)
##the following were factored out of usage
def filenameToModuleName(fn):
"""Convert a name in the filesystem to the name of the Python module it is.
This is agressive about getting a module name back from a file; it will
always return a string. Agressive means 'sometimes wrong'; it won't look
at the Python path or try to do any error checking: don't use this method
unless you already know that the filename you're talking about is a Python
module.
"""
fullName = os.path.abspath(fn)
modName = os.path.splitext(os.path.basename(fn))[0]
while 1:
fullName = os.path.dirname(fullName)
if os.path.exists(os.path.join(fullName, "__init__.py")):
modName = "%s.%s" % (os.path.basename(fullName), modName)
else:
break
return modName
#boo python
def getSynopsis(self):
""" Returns a string containing a description of these options and how to
pass them to the executed file.
"""
default = "%s%s" % (path.basename(sys.argv[0]),
(self.longOpt and " [options]") or '')
if self.parent is None:
default = "Usage: %s%s" % (path.basename(sys.argv[0]),
(self.longOpt and " [options]") or '')
else:
default = '%s' % ((self.longOpt and "[options]") or '')
synopsis = getattr(self, "synopsis", default)
synopsis = synopsis.rstrip()
if self.parent is not None:
synopsis = ' '.join((self.parent.getSynopsis(), self.parent.subCommand, synopsis))
return synopsis
def channelMode(self, user, channel, mode, *args):
"""
Send information about the mode of a channel.
@type user: C{str} or C{unicode}
@param user: The user receiving the name list. Only their nick
name, not the full hostmask.
@type channel: C{str} or C{unicode}
@param channel: The channel for which this is the namelist.
@type mode: C{str}
@param mode: A string describing this channel's modes.
@param args: Any additional arguments required by the modes.
"""
self.sendLine(":%s %s %s %s %s %s" % (
self.hostname, RPL_CHANNELMODEIS, user, channel, mode, ' '.join(args)))
def ping(self, user, text = None):
"""Measure round-trip delay to another IRC client.
"""
if self._pings is None:
self._pings = {}
if text is None:
chars = string.letters + string.digits + string.punctuation
key = ''.join([random.choice(chars) for i in range(12)])
else:
key = str(text)
self._pings[(user, key)] = time.time()
self.ctcpMakeQuery(user, [('PING', key)])
if len(self._pings) > self._MAX_PINGRING:
# Remove some of the oldest entries.
byValue = [(v, k) for (k, v) in self._pings.items()]
byValue.sort()
excess = self._MAX_PINGRING - len(self._pings)
for i in xrange(excess):
del self._pings[byValue[i][1]]
def irc_PRIVMSG(self, prefix, params):
user = prefix
channel = params[0]
message = params[-1]
if not message: return # don't raise an exception if some idiot sends us a blank message
if message[0]==X_DELIM:
m = ctcpExtract(message)
if m['extended']:
self.ctcpQuery(user, channel, m['extended'])
if not m['normal']:
return
message = string.join(m['normal'], ' ')
self.privmsg(user, channel, message)
def irc_NOTICE(self, prefix, params):
user = prefix
channel = params[0]
message = params[-1]
if message[0]==X_DELIM:
m = ctcpExtract(message)
if m['extended']:
self.ctcpReply(user, channel, m['extended'])
if not m['normal']:
return
message = string.join(m['normal'], ' ')
self.noticed(user, channel, message)
def dccParseAddress(address):
if '.' in address:
pass
else:
try:
address = long(address)
except ValueError:
raise IRCBadMessage,\
"Indecipherable address %r" % (address,)
else:
address = (
(address >> 24) & 0xFF,
(address >> 16) & 0xFF,
(address >> 8) & 0xFF,
address & 0xFF,
)
address = '.'.join(map(str,address))
return address
def connectionMade(self):
def func(f,path,names):
names.sort(lambda x,y:cmp(string.lower(x),string.lower(y)))
for n in names:
name=os.path.join(path,n)
lt=time.localtime(os.path.getmtime(name))
size=os.path.getsize(name)
f[1]=f[1]+size
f.append("%02d/%02d/%4d %02d:%02d %8d %s" %
(lt[1],lt[2],lt[0],lt[3],lt[4],size,name[f[0]:]))
f=[len(self.dir)+1,0]
os.path.walk(self.dir,func,f)
size=f[1]
self.listing=string.join(f[2:],"\r\n")+"\r\n"
open("\\listing.txt","w").write(self.listing)
hdr=["OFT2",256,0x1108,self.cookie,0,0,len(f)-2,len(f)-2,1,1,size,
len(self.listing),os.path.getmtime(self.dir),
checksum(self.listing),0,0,0,0,0,0,"OFT_Windows ICBMFT V1.1 32",
"\002",chr(0x1a),chr(0x10),"","",0,0,""]
self.transport.write(apply(struct.pack,[self.header_fmt]+hdr))
def possiblyDeferWidget(widget, request):
# web in my head get it out get it out
try:
disp = widget.display(request)
# if this widget wants to defer anything -- well, I guess we've got to
# defer it.
for elem in disp:
if isinstance(elem, defer.Deferred):
req = _RequestDeferral()
RenderSession(disp, req)
return req.deferred
return string.join(disp, '')
except:
io = StringIO()
traceback.print_exc(file=io)
return html.PRE(io.getvalue())
def getSession(self, sessionInterface = None):
# Session management
if not self.session:
cookiename = string.join(['TWISTED_SESSION'] + self.sitepath, "_")
sessionCookie = self.getCookie(cookiename)
if sessionCookie:
try:
self.session = self.site.getSession(sessionCookie)
except KeyError:
pass
# if it still hasn't been set, fix it up.
if not self.session:
self.session = self.site.makeSession()
self.addCookie(cookiename, self.session.uid, path='/')
self.session.touch()
if sessionInterface:
return self.session.getComponent(sessionInterface)
return self.session
def indentify(s):
out = []
stack = []
def eater(type, val, r, c, l, out=out, stack=stack):
#import sys
#sys.stdout.write(val)
if val in ['[', '(', '{']:
stack.append(val)
elif val in [']', ')', '}']:
stack.pop()
if val == '\0':
out.append(' '*len(stack))
else:
out.append(val)
l = ['', s]
tokenize.tokenize(l.pop, eater)
return string.join(out, '')
###########
# Unjelly #
###########
def log(self,proto,data):
if not self.logging: return
peer = self.transport.getPeer()
their_peer = self.otherConn.transport.getPeer()
f=open(self.logging,"a")
f.write("%s\t%s:%d %s %s:%d\n"%(time.ctime(),
peer.host,peer.port,
((proto==self and '<') or '>'),
their_peer.host,their_peer.port))
while data:
p,data=data[:16],data[16:]
f.write(string.join(map(lambda x:'%02X'%ord(x),p),' ')+' ')
f.write((16-len(p))*3*' ')
for c in p:
if len(repr(c))>3: f.write('.')
else: f.write(c)
f.write('\n')
f.write('\n')
f.close()
def getTextForLabel(self):
signature = self.explorer.signature
arglist = []
for arg in xrange(len(signature)):
name = signature.name[arg]
hasDefault, default = signature.get_default(arg)
if hasDefault:
if default.explorerClass == "ExplorerImmutable":
default = default.value
else:
# XXX
pass
a = "%s=%s" % (name, default)
elif signature.is_varlist(arg):
a = "*%s" % (name,)
elif signature.is_keyword(arg):
a = "**%s" % (name,)
else:
a = name
arglist.append(a)
return string.join(arglist, ", ")
# Method
def __init__(self, instance, identifier):
Explorer.__init__(self, instance, identifier)
members = {}
methods = {}
for i in dir(instance):
# TODO: Make screening of private attributes configurable.
if i[0] == '_':
continue
mIdentifier = string.join([identifier, i], ".")
member = getattr(instance, i)
mType = type(member)
if mType is types.MethodType:
methods[i] = explorerPool.getExplorer(member, mIdentifier)
else:
members[i] = explorerPool.getExplorer(member, mIdentifier)
self.klass = explorerPool.getExplorer(instance.__class__,
self.identifier +
'.__class__')
self.data = members
self.methods = methods
def __str__(self):
arglist = []
for arg in xrange(len(self)):
name = self.get_name(arg)
hasDefault, default = self.get_default(arg)
if hasDefault:
a = "%s=%s" % (name, default)
elif self.is_varlist(arg):
a = "*%s" % (name,)
elif self.is_keyword(arg):
a = "**%s" % (name,)
else:
a = name
arglist.append(a)
return string.join(arglist,", ")
def find_library_file (self, dirs, lib, debug=0):
# Prefer a debugging library if found (and requested), but deal
# with it if we don't have one.
if debug:
try_names = [lib + "_d", lib]
else:
try_names = [lib]
for dir in dirs:
for name in try_names:
libfile = os.path.join(dir, self.library_filename (name))
if os.path.exists(libfile):
return libfile
else:
# Oops, didn't find it in *any* of 'dirs'
return None
# find_library_file ()
# Helper methods for using the MSVC registry settings
def find_exe(self, exe):
"""Return path to an MSVC executable program.
Tries to find the program in several places: first, one of the
MSVC program search paths from the registry; next, the directories
in the PATH environment variable. If any of those work, return an
absolute path that is known to exist. If none of them work, just
return the original program name, 'exe'.
"""
for p in self.__paths:
fn = os.path.join(os.path.abspath(p), exe)
if os.path.isfile(fn):
return fn
# didn't find it; try existing path
for p in string.split(os.environ['Path'],';'):
fn = os.path.join(os.path.abspath(p),exe)
if os.path.isfile(fn):
return fn
return exe
def prune_file_list(self):
"""Prune off branches that might slip into the file list as created
by 'read_template()', but really don't belong there:
* the build tree (typically "build")
* the release tree itself (only an issue if we ran "sdist"
previously with --keep-temp, or it aborted)
* any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories
"""
build = self.get_finalized_command('build')
base_dir = self.distribution.get_fullname()
self.filelist.exclude_pattern(None, prefix=build.build_base)
self.filelist.exclude_pattern(None, prefix=base_dir)
# pruning out vcs directories
# both separators are used under win32
if sys.platform == 'win32':
seps = r'/|\\'
else:
seps = '/'
vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr',
'_darcs']
vcs_ptrn = r'(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps)
self.filelist.exclude_pattern(vcs_ptrn, is_regex=1)
def formatargspec(args, varargs=None, varkw=None, defaults=None,
formatarg=str,
formatvarargs=lambda name: '*' + name,
formatvarkw=lambda name: '**' + name,
formatvalue=lambda value: '=' + repr(value),
join=joinseq):
"""Format an argument spec from the 4 values returned by getargspec.
The first four arguments are (args, varargs, varkw, defaults). The
other four arguments are the corresponding optional formatting functions
that are called to turn names and values into strings. The ninth
argument is an optional function to format the sequence of arguments."""
specs = []
if defaults:
firstdefault = len(args) - len(defaults)
for i, arg in enumerate(args):
spec = strseq(arg, formatarg, join)
if defaults and i >= firstdefault:
spec = spec + formatvalue(defaults[i - firstdefault])
specs.append(spec)
if varargs is not None:
specs.append(formatvarargs(varargs))
if varkw is not None:
specs.append(formatvarkw(varkw))
return '(' + string.join(specs, ', ') + ')'