本文整理汇总了Python中Foundation.NSString类的典型用法代码示例。如果您正苦于以下问题:Python NSString类的具体用法?Python NSString怎么用?Python NSString使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了NSString类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: handle_notification
def handle_notification(self, notification):
handler = getattr(self, '_NH_%s' % notification.name, Null)
handler(notification)
if notification.name in ('SIPEngineSIPTrace', 'SIPEngineLog', 'MSRPLibraryLog', 'MSRPTransportTrace'):
return
# notifications text view
if self.notificationsCheckBox.state() == NSOnState:
attribs = notification.data.__dict__.copy()
# remove some data that would be too big to log
if notification.name == "MSRPTransportTrace":
if len(attribs["data"]) > 30:
attribs["data"] = "<%i bytes>"%len(attribs["data"])
elif notification.name in ("FileTransferStreamGotChunk", "ScreenSharingStreamGotData"):
attribs["content"] = "..."
if attribs.has_key("data"):
attribs["data"] = "..."
attribs = ", ".join("%s=%s" % (k, v) for k, v in attribs.iteritems())
ts = notification.datetime
ts = ts.replace(microsecond=0) if type(ts) == datetime else ""
self.notificationsBytes += len(notification.name) + len(str(notification.sender)) + len(attribs) + len(str(ts))
self.notifications_unfiltered.append((NSString.stringWithString_(notification.name),
NSString.stringWithString_(str(notification.sender)),
NSString.stringWithString_(attribs),
NSString.stringWithString_(str(ts))))
self.renderNotifications()
示例2: pre_appdata_use_startup
def pre_appdata_use_startup(appdata_path):
preload_dlls(unhandled_exc_handler)
try:
DOMAIN = NSString.alloc().initWithString_('com.apple.LaunchServices')
KEYS = (NSString.alloc().initWithString_('LSArchitecturesForX86_64'), NSString.alloc().initWithString_('LSArchitecturesForX86_64v2'))
APP = NSString.alloc().initWithString_('com.getdropbox.dropbox')
UserDefaults = NSUserDefaults.standardUserDefaults()
launchServices = UserDefaults.persistentDomainForName_(DOMAIN)
if launchServices:
for key in KEYS:
apps = launchServices.objectForKey_(key)
if apps and apps.get(APP):
apps.removeObjectForKey_(APP)
UserDefaults.setObject_forKey_(apps, key)
UserDefaults.setPersistentDomain_forName_(launchServices, DOMAIN)
UserDefaults.synchronize()
report_bad_assumption("User had 'Open using Rosetta' set.")
except Exception:
unhandled_exc_handler()
if MAC_VERSION <= LEOPARD:
try:
psn = ProcessSerialNumber()
Carbon.GetCurrentProcess(psn)
TRACE('On Leopard or lower: PSN is %r', (psn.lowLongOfPSN, psn.highLongOfPSN))
except Exception:
unhandled_exc_handler()
return arch.fixperms.check_and_fix_permissions(appdata_path)
示例3: input_box
def input_box(title):
box = NSAlert.alloc().init()
box.addButtonWithTitle_(NSString.alloc().initWithString_("OK"))
box.setMessageText_(NSString.alloc().initWithString_(title))
textbox = NSTextField.alloc().initWithFrame_(NSMakeRect(0, 0, 200, 24));
box.setAccessoryView_(textbox)
box.runModal()
return textbox.stringValue()
示例4: volume_list
def volume_list(folders, delegate):
volumes = NSMutableArray.alloc().init()
volumes.addObject_(NSString.alloc().initWithString_(os.path.expanduser('~/Ubuntu One')))
volumes.addObject_(NSString.alloc().initWithString_(os.path.expanduser('/Users/jose/Library/Application Support/ubuntuone')))
for folder in folders:
if (bool(folder['subscribed'])):
volumes.addObject_(NSString.alloc().initWithString_(folder['path']))
delegate.returnedVolumeList_(volumes)
示例5: add
def add(self, label, uri, index=-1):
if label in self.labels:
return
if index == -1 or index > len(self.items):
index = len(self.items)
elif index < -1:
index = 0
new_item = NSDictionary.alloc().initWithDictionary_(
dict(
Name=NSString.alloc().initWithString_(label),
URL=NSString.alloc().initWithString_(uri)
)
)
self.items.insert(index, new_item)
self.labels.append(label)
示例6: show_text
def show_text(self, text):
x, y = self._ns_path.currentPoint()
font = self._font
ns_font = font._ns_font
ns_color = self._textcolor._ns_color
ns_string = NSString.stringWithString_(text)
ns_attrs = {
NSFontAttributeName: ns_font,
NSForegroundColorAttributeName: ns_color,
}
# print "Canvas.show_text:", repr(text) ###
# print "family:", ns_font.familyName() ###
# print "size:", ns_font.pointSize() ###
# print "ascender:", ns_font.ascender() ###
# print "descender:", ns_font.descender() ###
# print "capHeight:", ns_font.capHeight() ###
# print "leading:", ns_font.leading() ###
# print "matrix:", ns_font.matrix() ###
# print "defaultLineHeightForFont:", ns_font.defaultLineHeightForFont() ###
h = ns_font.defaultLineHeightForFont()
d = -ns_font.descender()
dy = h - d
if ns_font.familyName() == "Courier New":
dy += ns_font.pointSize() * 0.229167
ns_point = NSPoint(x, y - dy)
#print "drawing at:", ns_point ###
ns_string.drawAtPoint_withAttributes_(ns_point, ns_attrs)
dx = ns_font.widthOfString_(ns_string)
#self._ns_path.relativeMoveToPoint_(NSPoint(x + dx, y))
self._ns_path.relativeMoveToPoint_((dx, 0))
示例7: _GetSystemProfile
def _GetSystemProfile(self, sp_type):
# pylint: disable=global-statement
if sp_type not in self._cache:
logging.debug('%s not cached', sp_type)
sp_xml = self._GetSystemProfilerOutput(sp_type)
self._cache[sp_type] = NSString.stringWithString_(sp_xml).propertyList()
return self._cache[sp_type]
示例8: requiredThickness
def requiredThickness(self):
lineCount = len(self.lineIndices())
digits = int(math.log10(lineCount) + 1)
sampleString = NSString.stringWithString_("8" * digits)
stringSize = sampleString.sizeWithAttributes_(self.textAttributes())
return math.ceil(max([self.DEFAULT_THICKNESS, stringSize.width + self.RULER_MARGIN * 2]))
示例9: _update_view_with_string
def _update_view_with_string(self, str_data):
ns_str = NSString.stringWithString_(str_data.decode('latin-1'))
data = ns_str.dataUsingEncoding_(NSISOLatin1StringEncoding)
url = NSURL.URLWithString_('about:blank')
frame = self.web_view.mainFrame()
frame.loadData_MIMEType_textEncodingName_baseURL_(data, 'text/plain',
'latin-1', url)
示例10: DSQuery
def DSQuery(dstype, objectname, attribute=None):
"""DirectoryServices query.
Args:
dstype: The type of objects to query. user, group.
objectname: the object to query.
attribute: the optional attribute to query.
Returns:
If an attribute is specified, the value of the attribute. Otherwise, the
entire plist.
Raises:
DSException: Cannot query DirectoryServices.
"""
ds_path = "/%ss/%s" % (dstype.capitalize(), objectname)
cmd = [_DSCL, "-plist", ".", "-read", ds_path]
if attribute:
cmd.append(attribute)
(stdout, stderr, returncode) = RunProcess(cmd)
if returncode:
raise DSException("Cannot query %s for %s: %s" % (ds_path, attribute, stderr))
plist = NSString.stringWithString_(stdout).propertyList()
if attribute:
value = None
if "dsAttrTypeStandard:%s" % attribute in plist:
value = plist["dsAttrTypeStandard:%s" % attribute]
elif attribute in plist:
value = plist[attribute]
try:
# We're copying to a new list to convert from NSCFArray
return value[:]
except TypeError:
# ... unless we can't
return value
else:
return plist
示例11: load_dictionaries
def load_dictionaries(context_ref, language_list):
# The function is a bit picky about making sure we pass a clean NSArray with NSStrings
langs = NSMutableArray.array()
for x in language_list:
langs.addObject_(NSString.stringWithString_(x))
# The True argument is for whether the language string objects are already retained
SFPWAContextLoadDictionaries(context_ref, langs, True)
示例12: DSQuery
def DSQuery(dstype, objectname, attribute):
"""DirectoryServices query.
Args:
dstype: The type of objects to query. user, group.
objectname: the object to query.
attribute: the attribute to query.
Returns:
the value of the attribute. If single-valued array, return single value.
Raises:
DSException: Cannot query DirectoryServices.
"""
ds_path = '/%ss/%s' % (dstype.capitalize(), objectname)
cmd = [_DSCL, '-plist', '.', '-read', ds_path, attribute]
task = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = task.communicate()
if task.returncode:
raise DSException('Cannot query %s for %s: %s' % (ds_path,
attribute,
stderr))
plist = NSString.stringWithString_(stdout).propertyList()
if 'dsAttrTypeStandard:%s' % attribute in plist:
value = plist['dsAttrTypeStandard:%s' % attribute]
if len(value) == 1:
return value[0]
else:
return value
else:
return None
示例13: drawHashMarksAndLabelsInRect_
def drawHashMarksAndLabelsInRect_(self, rect):
bounds = self.bounds()
view = self.clientView()
rulerBackgroundColor = self.rulerBackgroundColor()
if rulerBackgroundColor is not None:
rulerBackgroundColor.set()
NSRectFill(bounds)
if not isinstance(view, NSTextView):
return
layoutManager = view.layoutManager()
container = view.textContainer()
text = view.string()
nullRange = NSMakeRange(NSNotFound, 0)
yinset = view.textContainerInset().height
visibleRect = self.scrollView().contentView().bounds()
textAttributes = self.textAttributes()
lines = self.lineIndices()
glyphRange = layoutManager.glyphRangeForBoundingRect_inTextContainer_(visibleRect, container)
_range = layoutManager.characterRangeForGlyphRange_actualGlyphRange_(glyphRange, None)[0]
_range.length += 1
count = len(lines)
index = 0
lineNumber = self.lineNumberForCharacterIndex_inText_(_range.location, text)
for line in range(lineNumber, count):
index = lines[line]
if NSLocationInRange(index, _range):
rects, rectCount = layoutManager.rectArrayForCharacterRange_withinSelectedCharacterRange_inTextContainer_rectCount_(
NSMakeRange(index, 0),
nullRange,
container,
None
)
if rectCount > 0:
ypos = yinset + NSMinY(rects[0]) - NSMinY(visibleRect)
labelText = NSString.stringWithString_("%s" % (line + 1))
stringSize = labelText.sizeWithAttributes_(textAttributes)
x = NSWidth(bounds) - stringSize.width - self.RULER_MARGIN
y = ypos + (NSHeight(rects[0]) - stringSize.height) / 2.0
w = NSWidth(bounds) - self.RULER_MARGIN * 2.0
h = NSHeight(rects[0])
labelText.drawInRect_withAttributes_(NSMakeRect(x, y, w, h), textAttributes)
if index > NSMaxRange(_range):
break
path = NSBezierPath.bezierPath()
path.moveToPoint_((bounds.origin.x + bounds.size.width, bounds.origin.y))
path.lineToPoint_((bounds.origin.x + bounds.size.width, bounds.origin.y + bounds.size.height))
NSColor.grayColor().set()
path.stroke()
示例14: setLabel_
def setLabel_(self, label):
if type(label) == NSString:
self.label = label
else:
self.label = NSString.stringWithString_(label)
frame = self.frame()
frame.size.width = self.idealWidth()
self.setFrame_(frame)
示例15: DSSearch
def DSSearch(path, key, value, node='.'):
cmd = [_DSCL, node, '-search', path, key, value]
(stdout, stderr, returncode) = gmacpyutil.RunProcess(cmd)
if returncode:
raise DSException('Cannot search %s for %s:%s. %s' % (path,
key,
value,
stderr))
return NSString.stringWithString_(stdout)