Python string 模块,split() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用string.split()。
def wmfactory_directory(self, request):
m = []
for user in pwd.getpwall():
pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell \
= user
realname = string.split(pw_gecos,',')[0]
if not realname:
realname = pw_name
if os.path.exists(os.path.join(pw_dir, self.userDirName)):
m.append({
'href':'%s/'%pw_name,
'text':'%s (file)'%realname
})
twistdsock = os.path.join(pw_dir, self.userSocketName)
if os.path.exists(twistdsock):
linknm = '%s.twistd' % pw_name
m.append({
'href':'%s/'%linknm,
'text':'%s (twistd)'%realname})
return m
def getMessagePayload(self):
self.logger.debug("Preparing client->device message payload")
salon = -127
try:
salon = read_temp()
except Exception as e:
self.logger.error("error reading local temp")
self.logger.exception(e)
piwnica = -127
relay = 0
try:
os.system("sudo ifconfig eth0 192.168.1.101 netmask 255.255.255.0")
txt = urllib2.urlopen(relay1_addr).read()
lines = string.split(txt, '\n')
piwnica = float(lines[1])
relay = int(lines[0])
except Exception as e:
self.logger.error("error reading data from {0}".format(relay1_addr))
self.logger.exception(e)
payloadDict = {"values":{}}
payloadDict["values"]["relay"] = relay
if salon > -127:
payloadDict["values"]["salon"] = salon
if piwnica > -127:
payloadDict["values"]["piwnica"] = piwnica
payload = json.dumps(payloadDict)
return payload
def get_build_version():
"""Return the version of MSVC that was used to build Python.
For Python 2.3 and up, the version number is included in
sys.version. For earlier versions, assume the compiler is MSVC 6.
"""
prefix = "MSC v."
i = string.find(sys.version, prefix)
if i == -1:
return 6
i = i + len(prefix)
s, rest = sys.version[i:].split(" ", 1)
majorVersion = int(s[:-2]) - 6
minorVersion = int(s[2:3]) / 10.0
# I don't think paths are affected by minor version in version 6
if majorVersion == 6:
minorVersion = 0
if majorVersion >= 6:
return majorVersion + minorVersion
# else we don't know what version of the compiler this is
return None
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 _format_changelog(self, changelog):
"""Format the changelog correctly and convert it to a list of strings
"""
if not changelog:
return changelog
new_changelog = []
for line in string.split(string.strip(changelog), '\n'):
line = string.strip(line)
if line[0] == '*':
new_changelog.extend(['', line])
elif line[0] == '-':
new_changelog.append(line)
else:
new_changelog.append(' ' + line)
# strip trailing newline inserted by first changelog entry
if not new_changelog[0]:
del new_changelog[0]
return new_changelog
# _format_changelog()
# class bdist_rpm
def source_synopsis(file):
line = file.readline()
while line[:1] == '#' or not strip(line):
line = file.readline()
if not line: break
line = strip(line)
if line[:4] == 'r"""': line = line[1:]
if line[:3] == '"""':
line = line[3:]
if line[-1:] == '\\': line = line[:-1]
while not strip(line):
line = file.readline()
if not line: break
result = strip(split(line, '"""')[0])
else: result = None
return result
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 help(self, request):
if type(request) is type(''):
request = request.strip()
if request == 'help': self.intro()
elif request == 'keywords': self.listkeywords()
elif request == 'symbols': self.listsymbols()
elif request == 'topics': self.listtopics()
elif request == 'modules': self.listmodules()
elif request[:8] == 'modules ':
self.listmodules(split(request)[1])
elif request in self.symbols: self.showsymbol(request)
elif request in self.keywords: self.showtopic(request)
elif request in self.topics: self.showtopic(request)
elif request: doc(request, 'Help on %s:')
elif isinstance(request, Helper): self()
else: doc(request, 'Help on %s:')
self.output.write('\n')
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 pattern_scan(string):
words = string.split()
wcount = len(words)
eng_count = english_test(string)
print "\n\t\tNumber of Wrods : ", wcount
print "\n\t\tEnglish words =", eng_count
ratio = float("0.0")
ratio = float(eng_count)/float(wcount)
if (ratio > float("0.5")):
print "\n\t\t> The given string is a collection of English words"
return False
else :
return True
def _split(self, definition):
"""
In our YAML parameter definition line, split the key part from the value part.
:param definition: a parameter definition from our deployfish.yml
:type definition: string
:rtype: 2-tuple of strings
"""
key = definition
value = None
delimiter_loc = definition.find('=')
if delimiter_loc > 0:
key = definition[:delimiter_loc]
if len(definition) > delimiter_loc + 1:
value = definition[delimiter_loc + 1:].strip('"')
else:
value = ""
return (key, value)
def _getNetworksNetstatProto(self, proto) :
if(proto == "tcp") :
current_list = self.networks_netstat.list_tcp
argproto = "-t"
elif(proto == "udp") :
current_list = self.networks_netstat.list_udp
argproto = "-u"
i, o = os.popen2("/bin/netstat -an " + argproto)
j = o.readline()
j = o.readline()
j = o.readline()
while(j != ""):
liste = j.split()
if(proto == "tcp") :
current_list.append([liste[3], liste[4], liste[5]])
elif(proto == "udp") :
current_list.append([liste[3], liste[4], None])
j = o.readline()
o.close()
i.close()
def _getNetworksProcProto(self, proto) :
if(proto == "tcp") :
current_list = self.networks_proc.list_tcp
elif(proto == "udp") :
current_list = self.networks_proc.list_udp
try :
fichier = open("/proc/net/" + proto, "r")
except IOError :
print "No such file /proc/net/" + proto
sys.exit(-1)
liste = fichier.readlines()
fichier.close()
liste.pop(0)
for i in liste :
l = string.split(i)
if(proto == "tcp") :
current_list.append([self._iphexatodec(l[1]), self._iphexatodec(l[2]), self.tranlateState[l[3]]])
elif(proto == "udp") :
current_list.append([self._iphexatodec(l[1]), self._iphexatodec(l[2]), None])
def parsePhrase(self, phrase):
"""Decode the phrase, and return a 64bit OTP
I will raise Unauthorized if the parity is wrong
TODO: Add support for hex (MUST) and the '2nd scheme'(SHOULD)"""
words = string.split(phrase)
for i in xrange(len(words)):
words[i] = string.upper(words[i])
b = 0L
for i in xrange(0,5):
b = b | ((long(dict.index(words[i])) << ((4-i)*11L+9L)))
tmp = dict.index(words[5])
b = b | (tmp & 0x7FC ) >> 2
if (tmp & 3) <> self.calculateParity(b):
raise Unauthorized("Parity error")
digest = longToString(b)
return digest
def irc_RPL_NAMREPLY(self,prefix,params):
"""
RPL_NAMREPLY
>> NAMES #bnl
<< :Arlington.VA.US.Undernet.Org 353 z3p = #bnl :pSwede Dan-- SkOyg AG
"""
group=string.lower(params[2][1:])
users=string.split(params[3])
for ui in range(len(users)):
while users[ui][0] in ["@","+"]: # channel modes
users[ui]=users[ui][1:]
if not self._namreplies.has_key(group):
self._namreplies[group]=[]
self._namreplies[group].extend(users)
for nickname in users:
try:
self._ingroups[nickname].append(group)
except:
self._ingroups[nickname]=[group]
def parsemsg(s):
"""Breaks a message from an IRC server into its prefix, command, and arguments.
"""
prefix = ''
trailing = []
if not s:
raise IRCBadMessage("Empty line.")
if s[0] == ':':
prefix, s = s[1:].split(' ', 1)
if s.find(' :') != -1:
s, trailing = s.split(' :', 1)
args = s.split()
args.append(trailing)
else:
args = s.split()
command = args.pop(0)
return prefix, command, args
def split(str, length = 80):
"""I break a message into multiple lines.
I prefer to break at whitespace near str[length]. I also break at \\n.
@returns: list of strings
"""
if length <= 0:
raise ValueError("Length must be a number greater than zero")
r = []
while len(str) > length:
w, n = str[:length].rfind(' '), str[:length].find('\n')
if w == -1 and n == -1:
line, str = str[:length], str[length:]
else:
i = n == -1 and w or n
line, str = str[:i], str[i+1:]
r.append(line)
if len(str):
r.extend(str.split('\n'))
return r
def ctcpQuery_DCC(self, user, channel, data):
"""Initiate a Direct Client Connection
"""
if not data: return
dcctype = data.split(None, 1)[0].upper()
handler = getattr(self, "dcc_" + dcctype, None)
if handler:
if self.dcc_sessions is None:
self.dcc_sessions = []
data = data[len(dcctype)+1:]
handler(user, channel, data)
else:
nick = string.split(user,"!")[0]
self.ctcpMakeReply(nick, [('ERRMSG',
"DCC %s :Unknown DCC type '%s'"
% (data, dcctype))])
self.quirkyMessage("%s offered unknown DCC type %s"
% (user, dcctype))
def modeTocSignon(self):
flap=self.readFlap()
if flap==None:
return "TocSignon"
if flap[0]!=DATA: raise TOCParseError
data=string.split(flap[1]," ")
if data[0]!="toc_signon": raise TOCParseError
for i in data:
if not i:data.remove(i)
password=unroast(data[4])
if not(self.authorize(data[1],int(data[2]),data[3],password)):
self.sendError(BAD_NICKNAME)
self.transport.loseConnection()
return
self.sendFlap(DATA,"SIGN_ON:TOC1.0")
self.sendFlap(DATA,"NICK:%s"%self.saved.nick)
self.sendFlap(DATA,"CONFIG:%s"%self.saved.config)
# sending user configuration goes here
return "Connected"
def modeConnected(self):
flap=self.readFlap()
while flap!=None:
if flap[0] not in [DATA,KEEP_ALIVE]: raise TOCParseError
flapdata=string.split(flap[1]," ",1)
tocname=flapdata[0][4:]
if len(flapdata)==2:
data=flapdata[1]
else:
data=""
func=getattr(self,"toc_"+tocname,None)
if func!=None:
func(data)
else:
self.toc_unknown(tocname,data)
flap=self.readFlap()
return "Connected"
def toc_add_buddy(self,data):
"""
adds users to the buddy list
toc_add_buddy <buddyname1> [<buddyname2>] [<buddyname3>]...
"""
buddies=map(normalize,string.split(data," "))
for b in buddies:
if b not in self.buddylist:
self.buddylist.append(b)
for buddy in buddies:
try:
buddy=self.factory.users[buddy]
except:
pass
else:
self.buddyUpdate(buddy)
def toc_send_im(self,data):
"""
incoming instant message
toc_send_im <screenname> <quoted message> [auto]
"""
username,data=string.split(data," ",1)
auto=0
if data[-4:]=="auto":
auto=1
data=data[:-5]
data=unquote(data)
if not(self.factory.users.has_key(username)):
self.sendError(NOT_AVAILABLE,username)
return
user=self.factory.users[username]
if not(self.canContact(user)):
self.sendError(NOT_AVAILABLE,username)
return
user.hearWhisper(self,data,auto)
def __init__(self, path, defaultType="text/html", ignoredExts=(), registry=None, allowExt=0):
"""Create a file with the given path.
"""
resource.Resource.__init__(self)
filepath.FilePath.__init__(self, path)
# Remove the dots from the path to split
self.defaultType = defaultType
if ignoredExts in (0, 1) or allowExt:
warnings.warn("ignoredExts should receive a list, not a boolean")
if ignoredExts or allowExt:
self.ignoredExts = ['*']
else:
self.ignoredExts = []
else:
self.ignoredExts = list(ignoredExts)
self.registry = registry or Registry()
def lineReceived(self, line):
parts = string.split(line)
if not parts:
parts = ['']
if len(parts) == 1:
slash_w = 0
else:
slash_w = 1
user = parts[-1]
if '@' in user:
host_place = string.rfind(user, '@')
user = user[:host_place]
host = user[host_place+1:]
return self.forwardQuery(slash_w, user, host)
if user:
return self.getUser(slash_w, user)
else:
return self.getDomain(slash_w)
def get_build_version():
"""Return the version of MSVC that was used to build Python.
For Python 2.3 and up, the version number is included in
sys.version. For earlier versions, assume the compiler is MSVC 6.
"""
prefix = "MSC v."
i = string.find(sys.version, prefix)
if i == -1:
return 6
i = i + len(prefix)
s, rest = sys.version[i:].split(" ", 1)
majorVersion = int(s[:-2]) - 6
minorVersion = int(s[2:3]) / 10.0
# I don't think paths are affected by minor version in version 6
if majorVersion == 6:
minorVersion = 0
if majorVersion >= 6:
return majorVersion + minorVersion
# else we don't know what version of the compiler this is
return None
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 source_synopsis(file):
line = file.readline()
while line[:1] == '#' or not strip(line):
line = file.readline()
if not line: break
line = strip(line)
if line[:4] == 'r"""': line = line[1:]
if line[:3] == '"""':
line = line[3:]
if line[-1:] == '\\': line = line[:-1]
while not strip(line):
line = file.readline()
if not line: break
result = strip(split(line, '"""')[0])
else: result = None
return result
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
else:
object = __builtin__
for part in parts[n:]:
try:
object = getattr(object, part)
except AttributeError:
return None
return object
# --------------------------------------- interactive interpreter interface
def help(self, request):
if type(request) is type(''):
request = request.strip()
if request == 'help': self.intro()
elif request == 'keywords': self.listkeywords()
elif request == 'symbols': self.listsymbols()
elif request == 'topics': self.listtopics()
elif request == 'modules': self.listmodules()
elif request[:8] == 'modules ':
self.listmodules(split(request)[1])
elif request in self.symbols: self.showsymbol(request)
elif request in self.keywords: self.showtopic(request)
elif request in self.topics: self.showtopic(request)
elif request: doc(request, 'Help on %s:')
elif isinstance(request, Helper): self()
else: doc(request, 'Help on %s:')
self.output.write('\n')
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 _processSentence(self, elem, sessionID):
"""Process a <sentence> AIML element.
<sentence> elements process their contents recursively, and
then capitalize the first letter of the results.
"""
response = ""
for e in elem[2:]:
response += self._processElement(e, sessionID)
try:
response = response.strip()
words = string.split(response, " ", 1)
words[0] = string.capitalize(words[0])
response = string.join(words)
return response
except IndexError: # response was empty
return ""
# <set>
def fetch_symbol_images():
symbols_images = {}
source_image_path = "../zener-images"
for root, dirs, files in os.walk(source_image_path):
for f in files:
if f.endswith(".png"):
image_name = string.split(f, ".")
image = Image.open(source_image_path + "/" + f)
symbols_images[image_name[0]] = image
return symbols_images
# https://github.com/nathancahill/snippets/blob/master/image_perspective.py
# pa - starting points
# pb - ending points
# func will find the relevant coeffs that will result in the transformation of pa to pb
# and this will be used to transform the entire image
def __init__(self, control):
""" Initializes the SoundDRF class."""
self.control = control
ch = string.split(self.control.channel, ':')
self.channel = ch[0]
self.sub_channel = int(ch[1])
# open digital RF path
self.dio = drf.DigitalRFReader(self.control.path)
if self.control.verbose:
print 'channel bounds:', self.dio.get_bounds(self.channel)
self.bounds = self.dio.get_bounds(self.channel)
print 'bounds ', self.bounds
def encode_name(name, type, scope):
if name == '*':
name += '\0' * 15
elif len(name) > 15:
name = name[:15] + chr(type)
else:
name = string.ljust(name, 15) + chr(type)
encoded_name = chr(len(name) * 2) + re.sub('.', _do_first_level_encoding, name)
if scope:
encoded_scope = ''
for s in string.split(scope, '.'):
encoded_scope = encoded_scope + chr(len(s)) + s
return encoded_name + encoded_scope + '\0'
else:
return encoded_name.encode('ascii') + '\0'
# Internal method for use in encode_name()
def _clean_terminals(self):
"""
Because of the optimization, there are some non existing terminals
on the generated list. Remove them by checking for terms in form Ax,x
"""
new_terminals = []
for term in self.grammar.grammar_terminals:
x_term = term.rfind('@')
y_term = term.rfind('A')
if y_term > x_term:
x_term = y_term
ids = term[x_term + 1:].split(',')
if len(ids) < 2:
"""It'input_string a normal terminal, not a state"""
new_terminals.append(term)
self.grammar.grammar_terminals = new_terminals
def _check_self_to_empty(self, stateid):
"""
Because of the optimization, the rule for empty states is missing
A check takes place live
Args:
stateid (int): The state identifier
Returns:
bool: A true or false response
"""
x_term = stateid.rfind('@')
y_term = stateid.rfind('A')
if y_term > x_term:
x_term = y_term
ids = stateid[x_term + 1:].split(',')
if len(ids) < 2:
return 0
if ids[0] == ids[1]:
# print 'empty'
return 1
return 0
def strtoip(ipstr):
"""convert an IP address in string form to numeric."""
res = 0L
count = 0
n = string.split(ipstr, '.')
for i in n:
res = res << 8L
ot = string.atoi(i)
if ot < 0 or ot > 255:
raise ValueError, "invalid IP octet"
res = res + ot
count = count + 1
# could be incomplete (short); make it complete.
while count < 4:
res = res << 8L
count = count + 1
return res
def cidrstrerr(str):
"""Check an IP address or CIDR netblock for validity.
Returns None if it is and otherwise an error string."""
if not cvalid.match(str):
return 'Not a syntatically valid IP address or netblock'
rng = 32
pos = string.find(str, '/')
ips = str
if not pos == -1:
rng = string.atoi(ips[pos+1:])
ips = str[:pos]
if rng < 0 or rng > 32:
return 'CIDR length out of range'
n = string.split(ips, '.')
for i in n:
ip = string.atoi(i)
if (ip < 0 or ip > 255):
return 'an IP octet is out of range'
# could check to see if it is 'proper', but.
return None
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 startTunnel(self, remotePort, localPort, addr):
sshPrivateKeyFile = self.config.get('client', 'sshPrivateKeyFile')
self.logger.info("Opening SSH tunneling session for remotePort={0}, localPort={1}, addr={2} using privateKey={3}".format(remotePort, localPort, addr, sshPrivateKeyFile))
cmd = "/usr/bin/ssh -o BatchMode=yes -o StrictHostKeyChecking=no -i {0} -N -R {1}:localhost:{2} {3}".format(sshPrivateKeyFile, remotePort, localPort, addr)
self.logger.info("Starting process: {0}".format(cmd))
self.tunnel = Popen(cmd.split())
self.logger.info("SSH tunneling process started")
def get_msvc_paths(self, path, platform='x86'):
"""Get a list of devstudio directories (include, lib or path).
Return a list of strings. The list will be empty if unable to
access the registry or appropriate registry keys not found.
"""
if not _can_read_reg:
return []
path = path + " dirs"
if self.__version >= 7:
key = (r"%s\%0.1f\VC\VC_OBJECTS_PLATFORM_INFO\Win32\Directories"
% (self.__root, self.__version))
else:
key = (r"%s\6.0\Build System\Components\Platforms"
r"\Win32 (%s)\Directories" % (self.__root, platform))
for base in HKEYS:
d = read_values(base, key)
if d:
if self.__version >= 7:
return string.split(self.__macros.sub(d[path]), ";")
else:
return string.split(d[path], ";")
# MSVC 6 seems to create the registry entries we need only when
# the GUI is run.
if self.__version == 6:
for base in HKEYS:
if read_values(base, r"%s\6.0" % self.__root) is not None:
self.warn("It seems you have Visual Studio 6 installed, "
"but the expected registry settings are not present.\n"
"You must at least run the Visual Studio GUI once "
"so that these entries are created.")
break
return []
def get_ext_fullpath(self, ext_name):
"""Returns the path of the filename for a given extension.
The file is located in `build_lib` or directly in the package
(inplace option).
"""
# makes sure the extension name is only using dots
all_dots = string.maketrans('/'+os.sep, '..')
ext_name = ext_name.translate(all_dots)
fullname = self.get_ext_fullname(ext_name)
modpath = fullname.split('.')
filename = self.get_ext_filename(ext_name)
filename = os.path.split(filename)[-1]
if not self.inplace:
# no further work needed
# returning :
# build_dir/package/path/filename
filename = os.path.join(*modpath[:-1]+[filename])
return os.path.join(self.build_lib, filename)
# the inplace option requires to find the package directory
# using the build_py command for that
package = '.'.join(modpath[0:-1])
build_py = self.get_finalized_command('build_py')
package_dir = os.path.abspath(build_py.get_package_dir(package))
# returning
# package_dir/filename
return os.path.join(package_dir, filename)
def get_export_symbols (self, ext):
"""Return the list of symbols that a shared extension has to
export. This either uses 'ext.export_symbols' or, if it's not
provided, "init" + module_name. Only relevant on Windows, where
the .pyd file (DLL) must export the module "init" function.
"""
initfunc_name = "init" + ext.name.split('.')[-1]
if initfunc_name not in ext.export_symbols:
ext.export_symbols.append(initfunc_name)
return ext.export_symbols
def handle_extra_path (self):
if self.extra_path is None:
self.extra_path = self.distribution.extra_path
if self.extra_path is not None:
if type(self.extra_path) is StringType:
self.extra_path = string.split(self.extra_path, ',')
if len(self.extra_path) == 1:
path_file = extra_dirs = self.extra_path[0]
elif len(self.extra_path) == 2:
(path_file, extra_dirs) = self.extra_path
else:
raise DistutilsOptionError, \
("'extra_path' option must be a list, tuple, or "
"comma-separated string with 1 or 2 elements")
# convert to local form in case Unix notation used (as it
# should be in setup scripts)
extra_dirs = convert_path(extra_dirs)
else:
path_file = None
extra_dirs = ''
# XXX should we warn if path_file and not extra_dirs? (in which
# case the path file would be harmless but pointless)
self.path_file = path_file
self.extra_dirs = extra_dirs
# handle_extra_path ()
def convert_path (pathname):
"""Return 'pathname' as a name that will work on the native filesystem,
i.e. split it on '/' and put it back together again using the current
directory separator. Needed because filenames in the setup script are
always supplied in Unix style, and have to be converted to the local
convention before we can actually use them in the filesystem. Raises
ValueError on non-Unix-ish systems if 'pathname' either starts or
ends with a slash.
"""
if os.sep == '/':
return pathname
if not pathname:
return pathname
if pathname[0] == '/':
raise ValueError, "path '%s' cannot be absolute" % pathname
if pathname[-1] == '/':
raise ValueError, "path '%s' cannot end with '/'" % pathname
paths = string.split(pathname, '/')
while '.' in paths:
paths.remove('.')
if not paths:
return os.curdir
return os.path.join(*paths)
# convert_path ()
def rfc822_escape (header):
"""Return a version of the string escaped for inclusion in an
RFC-822 header, by ensuring there are 8 spaces space after each newline.
"""
lines = string.split(header, '\n')
header = string.join(lines, '\n' + 8*' ')
return header
def fixname(name, split=string.split):
# xmllib in 2.0 and later provides limited (and slightly broken)
# support for XML namespaces.
if " " not in name:
return name
return "{%s}%s" % tuple(split(name, " ", 1))
def splitdoc(doc):
"""Split a doc string into a synopsis line (if any) and the rest."""
lines = split(strip(doc), '\n')
if len(lines) == 1:
return lines[0], ''
elif len(lines) >= 2 and not rstrip(lines[1]):
return lines[0], join(lines[2:], '\n')
return '', join(lines, '\n')