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
python类strip()的实例源码
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 __SkipRubish(self, aFilePathList):
"""
Edit this method to select the private file that will not be backed up.
"""
myFilteredList = []
for myFilePath in aFilePathList:
myLowerFilePath = string.lower(string.strip(myFilePath))
if myLowerFilePath[-4:]=='.obj':
continue
if myLowerFilePath[-5:]=='.class':
continue
if myLowerFilePath[-1:]=='~':
continue
myFilteredList.append(myFilePath)
return myFilteredList
def printexpr(expr_string):
""" printexpr(expr) -
print the value of the expression, along with linenumber and filename.
"""
stack = extract_stack ( )[-2:][0]
actualCall = stack[3]
left = string.find ( actualCall, '(' )
right = string.rfind ( actualCall, ')' )
caller_globals,caller_locals = _caller_symbols()
expr = eval(expr_string,caller_globals,caller_locals)
varType = type( expr )
stderr.write("%s:%d> %s == %s (%s)\n" % (
stack[0], stack[1],
string.strip( actualCall[left+1:right] )[1:-1],
repr(expr), str(varType)[7:-2]))
def _ParseWhois_Generic(self, fields):
for field in fields:
regex = "%s: *(.+)" % field['page_field']
#print regex
if field['rec_field'] == "servers":
self.servers = []
servers = re.findall(regex, self.page)
for server in servers:
try:
server = string.strip(server)
ip = socket.gethostbyname(server)
except:
ip = "?"
self.servers.append((server, ip))
else:
m = re.search(regex, self.page)
#if m: print m.group(1)
if m: setattr(self, field['rec_field'], string.strip(m.group(1)))
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 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 _syscmd_uname(option,default=''):
""" Interface to the system's uname command.
"""
if sys.platform in ('dos','win32','win16','os2'):
# XXX Others too ?
return default
try:
f = os.popen('uname %s 2> %s' % (option, DEV_NULL))
except (AttributeError,os.error):
return default
output = string.strip(f.read())
rc = f.close()
if not output or rc:
return default
else:
return output
def write(self, group=0):
"""Write the whole thing to string"""
t = []
if len(self.data) == 0:
return None
t.append('feature %s {' % self.type)
for src, dst in self.data:
if isinstance(src, (list, tuple)):
if group:
src = "[%s]" % string.join(src, ' ')
else:
src = string.join(src, ' ')
if isinstance(dst, (list, tuple)):
if group:
dst = "[%s]" % string.join(dst, ' ')
else:
dst = string.join(dst, ' ')
src = string.strip(src)
dst = string.strip(dst)
t.append("\tsub %s by %s;" % (src, dst))
t.append('}%s;' % self.type)
return string.join(t, '\n')
def Get_Line_Pairs(self,str):
line=0
line_pairs=dxflinepairsClass([])
#Start bei der ersten SECTION
while (find(str[line],"SECTION")<0):
line+=1
line-=1
#Durchlauf bis zum Ende falls kein Fehler auftritt. Ansonsten abbruch am Fehler
try:
while line < len(str):
line_pairs.line_pair.append(dxflinepairClass(int(strip(str[line])),strip(str[line+1])))
line+=2
except:
showwarning("Warning reading linepairs",("Failure reading line stopped at line %0.0f.\n Please check/correct line in dxf file" %(line)))
self.textbox.prt(("\n!Warning! Failure reading lines stopped at line %0.0f.\n Please check/correct line in dxf file\n " %(line)))
line_pairs.nrs=len(line_pairs.line_pair)
return line_pairs
#Suchen der Sectionen innerhalb des DXF-Files ntig um Blcke zu erkennen.
def Get_Line_Pairs(self,str):
line=0
line_pairs=dxflinepairsClass([])
#Start bei der ersten SECTION
while (find(str[line],"SECTION")<0):
line+=1
line-=1
#Durchlauf bis zum Ende falls kein Fehler auftritt. Ansonsten abbruch am Fehler
try:
while line < len(str):
line_pairs.line_pair.append(dxflinepairClass(int(strip(str[line])),strip(str[line+1])))
line+=2
except:
showwarning("Warning reading linepairs",("Failure reading line stopped at line %0.0f.\n Please check/correct line in dxf file" %(line)))
self.textbox.prt(("\n!Warning! Failure reading lines stopped at line %0.0f.\n Please check/correct line in dxf file\n " %(line)))
line_pairs.nrs=len(line_pairs.line_pair)
return line_pairs
#Suchen der Sectionen innerhalb des DXF-Files ntig um Blcke zu erkennen.
def load_from_triage_string(self, strTriage):
splitOnEq = string.split(strTriage, "=")
self.strFrame = splitOnEq[0]
self.strFollowup = string.strip(splitOnEq[1])
splitOnBang = string.split(splitOnEq[0], "!")
self.strModule = "*"
self.strRoutine = "*"
if(len(splitOnBang) > 1):
self.strModule = splitOnBang[0]
self.strRoutine = splitOnBang[1]
elif self.strFrame.endswith("*"):
self.strModule = self.strFrame.rstrip("*")
elif self.strFrame.startswith("*"):
self.strRoutine = self.strFrame.lstrip("*")
else:
self.strModule = self.strFrame
self.bExactModule = "*" not in self.strModule
self.bExactRoutine = "*" not in self.strRoutine
self.bExactFrame = self.bExactModule and self.bExactRoutine
def _count_grids(self):
self.num_grids = None
test_grid = test_grid_id = None
self.num_stars = 0
for line in rlines(open(self.index_filename, "rb")):
if line.startswith("BaryonFileName") or \
line.startswith("ParticleFileName") or \
line.startswith("FileName "):
test_grid = line.split("=")[-1].strip().rstrip()
if line.startswith("NumberOfStarParticles"):
self.num_stars = int(line.split("=")[-1])
if line.startswith("Grid "):
if self.num_grids is None:
self.num_grids = int(line.split("=")[-1])
test_grid_id = int(line.split("=")[-1])
if test_grid is not None:
break
self._guess_dataset_type(self.ds.dimensionality, test_grid, test_grid_id)
def load_variables(export_dir,variable_uses):
variables = []
try:
file = open(export_dir + "variables.txt","r")
var_list = file.readlines()
file.close()
for v in var_list:
vv = string.strip(v)
if vv:
variables.append(vv)
except:
print "variables.txt not found. Creating new variables.txt file"
try:
file = open(export_dir + "variable_uses.txt","r")
var_list = file.readlines()
file.close()
for v in var_list:
vv = string.strip(v)
if vv:
variable_uses.append(int(vv))
except:
print "variable_uses.txt not found. Creating new variable_uses.txt file"
return variables
def load_tag_uses(export_dir):
tag_uses = []
for i in xrange(tags_end):
sub_tag_uses = []
tag_uses.append(sub_tag_uses)
try:
file = open(export_dir + "tag_uses.txt","r")
var_list = file.readlines()
file.close()
for v in var_list:
vv = string.strip(v).split(';')
if vv:
for v2 in vv:
vvv = v2.split(' ')
if len(vvv) >= 3:
ensure_tag_use(tag_uses,int(vvv[0]),int(vvv[1]))
tag_uses[int(vvv[0])][int(vvv[1])] = int(vvv[2])
except:
print "Creating new tag_uses.txt file..."
return tag_uses
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 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 _syscmd_uname(option,default=''):
""" Interface to the system's uname command.
"""
if sys.platform in ('dos','win32','win16','os2'):
# XXX Others too ?
return default
try:
f = os.popen('uname %s 2> %s' % (option, DEV_NULL))
except (AttributeError,os.error):
return default
output = string.strip(f.read())
rc = f.close()
if not output or rc:
return default
else:
return output
def help(self,note=''):
self.print_header()
if self.synopsis:
print 'Synopsis:'
# To remain backward compatible:
try:
synopsis = self.synopsis % self.name
except (NameError, KeyError, TypeError):
synopsis = self.synopsis % self.__dict__
print ' ' + synopsis
print
self.print_options()
if self.version:
print 'Version:'
print ' %s' % self.version
print
if self.about:
print string.strip(self.about % self.__dict__)
print
if note:
print '-'*72
print 'Note:',note
print
def browse_search(selector, host, port):
while 1:
print '----- SEARCH -----'
print 'Selector:', repr(selector)
print 'Host:', host, ' Port:', port
print
try:
query = raw_input('Query [CR == up a level]: ')
except EOFError:
print
break
query = string.strip(query)
if not query:
break
if '\t' in query:
print 'Sorry, queries cannot contain tabs'
continue
browse_menu(selector + TAB + query, host, port)
# "Browse" telnet-based information, i.e. open a telnet session
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 help(self,note=''):
self.print_header()
if self.synopsis:
print 'Synopsis:'
# To remain backward compatible:
try:
synopsis = self.synopsis % self.name
except (NameError, KeyError, TypeError):
synopsis = self.synopsis % self.__dict__
print ' ' + synopsis
print
self.print_options()
if self.version:
print 'Version:'
print ' %s' % self.version
print
if self.about:
print string.strip(self.about % self.__dict__)
print
if note:
print '-'*72
print 'Note:',note
print
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 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 _syscmd_uname(option,default=''):
""" Interface to the system's uname command.
"""
if sys.platform in ('dos','win32','win16','os2'):
# XXX Others too ?
return default
try:
f = os.popen('uname %s 2> %s' % (option, DEV_NULL))
except (AttributeError,os.error):
return default
output = string.strip(f.read())
rc = f.close()
if not output or rc:
return default
else:
return output
def page_leave(self):
if self.lb_key_type.get_selected_index() == 0:
self.frontend.choices.gpg_key_type = "RSA"
self.frontend.choices.gpg_sub_key_type = "RSA"
else:
self.frontend.choices.gpg_key_type = "DSA"
self.frontend.choices.gpg_sub_key_type = "ELG-E"
self.frontend.choices.gpg_key_length = self.spn_key_length.get_value()
self.frontend.choices.gpg_password = self.txt_password.get_text()
self.frontend.choices.gpg_email = self.txt_email.get_text()
self.frontend.choices.gpg_name = self.txt_name.get_text()
self.frontend.choices.gpg_comment = self.txt_comment.get_text()
# TODO: implement entropy generator
self.frontend.choices.gpg_use_entropy_generator = True
self.frontend.choices.disable_password = self.chk_disable_password.get_active()
self.frontend.choices.gpg_key_expiry_date = datetime.datetime.strptime(string.strip(self.txt_key_expiry.get_text()), "%Y%m%d")
def validate(self):
key_expiry_parsed = False
try:
key_expiry = datetime.datetime.strptime(string.strip(self.txt_key_expiry.get_text()), "%Y%m%d")
key_expiry_parsed = True
except Exception, ex:
self.frontend.builder.root_widget.debugln("Didn't parse date: " + str(ex))
#TODO: alert user that their date doesn't parse
pass
if self.chk_disable_password.get_active() == True or \
(self.txt_password.get_text() == self.txt_password_confirm.get_text() and \
len(self.txt_password.get_text()) > 0 and \
key_expiry_parsed == True and \
key_expiry > datetime.datetime.now()):
self.frontend.gui_set_sensitive("btn_forward", True)
else:
self.frontend.gui_set_sensitive("btn_forward", False)
def _configure_tool(self, toolname):
"""Check if the specified tool is already on the device, otherwise install it."""
# Retrieve install options
tool = Constants.DEVICE_SETUP['TOOLS'][toolname]
try:
if tool['PACKAGES']:
# Install via apt-get
self.__install_package(toolname, tool)
elif tool['LOCAL']:
# Manual install
self.__install_local(toolname, tool)
elif tool['SETUP']:
# Use list of commands
self.__install_commands(toolname, tool)
else:
self.device.printer.debug('Installation method not provided for %s. Skipping' % toolname)
except Exception as e:
self.device.printer.warning('Error occurred during installation of tools: %s' % e.message.strip())
self.device.printer.warning('Trying to continue anyway...')
# ==================================================================================================================
# RUN
# ==================================================================================================================