本文整理汇总了Python中Foundation.NSDate类的典型用法代码示例。如果您正苦于以下问题:Python NSDate类的具体用法?Python NSDate怎么用?Python NSDate使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了NSDate类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _pyobjc_notify
def _pyobjc_notify(message, title=None, subtitle=None, appIcon=None, contentImage=None, open_URL=None, delay=0, sound=False):
swizzle(objc.lookUpClass('NSBundle'),
b'bundleIdentifier',
swizzled_bundleIdentifier)
notification = NSUserNotification.alloc().init()
notification.setInformativeText_(message)
if title:
notification.setTitle_(title)
if subtitle:
notification.setSubtitle_(subtitle)
if appIcon:
url = NSURL.alloc().initWithString_(appIcon)
image = NSImage.alloc().initWithContentsOfURL_(url)
notification.set_identityImage_(image)
if contentImage:
url = NSURL.alloc().initWithString_(contentImage)
image = NSImage.alloc().initWithContentsOfURL_(url)
notification.setContentImage_(image)
if sound:
notification.setSoundName_(
"NSUserNotificationDefaultSoundName")
notification.setDeliveryDate_(
NSDate.dateWithTimeInterval_sinceDate_(delay, NSDate.date()))
NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(
notification)
示例2: notify
def notify(title, subtitle, info_text, delay=0, sound=False, userInfo={}):
""" Python method to show a desktop notification on Mountain Lion. Where:
title: Title of notification
subtitle: Subtitle of notification
info_text: Informative text of notification
delay: Delay (in seconds) before showing the notification
sound: Play the default notification sound
userInfo: a dictionary that can be used to handle clicks in your
app's applicationDidFinishLaunching:aNotification method
"""
from Foundation import NSDate
from objc import lookUpClass
NSUserNotification = lookUpClass('NSUserNotification')
NSUserNotificationCenter = lookUpClass('NSUserNotificationCenter')
notification = NSUserNotification.alloc().init()
notification.setTitle_(title)
notification.setSubtitle_(subtitle)
notification.setInformativeText_(info_text)
notification.setUserInfo_(userInfo)
if sound:
notification.setSoundName_("NSUserNotificationDefaultSoundName")
notification.setDeliveryDate_(NSDate.dateWithTimeInterval_sinceDate_(delay, NSDate.date()))
NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)
示例3: notification
def notification(title, subtitle, message, data=None, sound=True, image=None):
"""Send a notification to Notification Center (Mac OS X 10.8+). If running on a version of Mac OS X that does not
support notifications, a ``RuntimeError`` will be raised. Apple says,
"The userInfo content must be of reasonable serialized size (less than 1k) or an exception will be thrown."
So don't do that!
:param title: text in a larger font.
:param subtitle: text in a smaller font below the `title`.
:param message: text representing the body of the notification below the `subtitle`.
:param data: will be passed to the application's "notification center" (see :func:`rumps.notifications`) when this
notification is clicked.
:param sound: whether the notification should make a noise when it arrives.
"""
if not _NOTIFICATIONS:
raise RuntimeError('Mac OS X 10.8+ is required to send notifications')
if data is not None and not isinstance(data, Mapping):
raise TypeError('notification data must be a mapping')
_require_string_or_none(title, subtitle, message)
notification = NSUserNotification.alloc().init()
notification.setTitle_(title)
notification.setSubtitle_(subtitle)
notification.setInformativeText_(message)
notification.setUserInfo_({} if data is None else data)
if sound:
notification.setSoundName_("NSUserNotificationDefaultSoundName")
if image != None:
notification.setContentImage_(image)
notification.setDeliveryDate_(NSDate.dateWithTimeInterval_sinceDate_(0, NSDate.date()))
NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)
示例4: send_OS_X_notify
def send_OS_X_notify(title, content, img_path):
'''发送Mac桌面通知'''
def swizzle(cls, SEL, func):
old_IMP = cls.instanceMethodForSelector_(SEL)
def wrapper(self, *args, **kwargs):
return func(self, old_IMP, *args, **kwargs)
new_IMP = objc.selector(wrapper, selector=old_IMP.selector,
signature=old_IMP.signature)
objc.classAddMethod(cls, SEL, new_IMP)
def swizzled_bundleIdentifier(self, original):
# Use iTunes icon for notification
return 'com.apple.itunes'
swizzle(objc.lookUpClass('NSBundle'),
b'bundleIdentifier',
swizzled_bundleIdentifier)
notification = NSUserNotification.alloc().init()
notification.setInformativeText_('')
notification.setTitle_(title.decode('utf-8'))
notification.setSubtitle_(content.decode('utf-8'))
notification.setInformativeText_('')
notification.setUserInfo_({})
if img_path is not None:
image = NSImage.alloc().initWithContentsOfFile_(img_path)
# notification.setContentImage_(image)
notification.set_identityImage_(image)
notification.setDeliveryDate_(
NSDate.dateWithTimeInterval_sinceDate_(0, NSDate.date())
)
NSUserNotificationCenter.defaultUserNotificationCenter().\
scheduleNotification_(notification)
示例5: software_updates_available
def software_updates_available(
self, force_check=False, suppress_check=False):
"""Checks for available Apple Software Updates, trying not to hit the
SUS more than needed.
Args:
force_check: Boolean. If True, forces a softwareupdate run.
suppress_check: Boolean. If True, skips a softwareupdate run.
Returns:
Integer. Count of available Apple updates.
"""
success = True
if suppress_check:
# don't check at all --
# typically because we are doing a logout install
# just return any AppleUpdates info we already have
if not os.path.exists(self.apple_updates_plist):
return 0
try:
plist = FoundationPlist.readPlist(self.apple_updates_plist)
except FoundationPlist.FoundationPlistException:
plist = {}
return len(plist.get('AppleUpdates', []))
if force_check:
# typically because user initiated the check from
# Managed Software Update.app
success = self.check_for_software_updates(force_check=True)
else:
# have we checked recently? Don't want to check with
# Apple Software Update server too frequently
now = NSDate.new()
next_su_check = now
last_su_check_string = prefs.pref(
'LastAppleSoftwareUpdateCheck')
if last_su_check_string:
try:
last_su_check = NSDate.dateWithString_(
last_su_check_string)
# dateWithString_ returns None if invalid date string.
if not last_su_check:
raise ValueError
interval = 24 * 60 * 60
# only force check every 24 hours.
next_su_check = last_su_check.dateByAddingTimeInterval_(
interval)
except (ValueError, TypeError):
pass
if now.timeIntervalSinceDate_(next_su_check) >= 0:
success = self.check_for_software_updates(force_check=True)
else:
success = self.check_for_software_updates(force_check=False)
display.display_debug1(
'CheckForSoftwareUpdates result: %s' % success)
if success:
count = self.write_appleupdates_file()
else:
self.clear_apple_update_info()
return 0
return count
示例6: format_time
def format_time(timestamp=None):
"""Return timestamp as an ISO 8601 formatted string, in the current
timezone.
If timestamp isn't given the current time is used."""
if timestamp is None:
return str(NSDate.new())
else:
return str(NSDate.dateWithTimeIntervalSince1970_(timestamp))
示例7: softwareupdated_installhistory
def softwareupdated_installhistory(start_date=None, end_date=None):
'''Returns softwareupdated items from InstallHistory.plist that are
within the given date range. (dates must be NSDates)'''
start_date = start_date or NSDate.distantPast()
end_date = end_date or NSDate.distantFuture()
try:
installhistory = FoundationPlist.readPlist(INSTALLHISTORY_PLIST)
except FoundationPlist.FoundationPlistException:
return []
return [item for item in installhistory
if item.get('processName') == 'softwareupdated'
and item['date'] >= start_date and item['date'] <= end_date]
示例8: notify
def notify(title, subtitle, msg_text, sound=False):
# Function to generate OS X notification.
NSUserNotification = lookUpClass("NSUserNotification")
NSUserNotificationCenter = lookUpClass("NSUserNotificationCenter")
notification = NSUserNotification.alloc().init()
notification.setTitle_(title)
notification.setSubtitle_(subtitle)
notification.setInformativeText_(msg_text)
if sound:
notification.setSoundName_("NSUserNotificationDefaultSoundName")
notification.setDeliveryDate_(NSDate.dateWithTimeInterval_sinceDate_(0, NSDate.date()))
NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)
示例9: thereAreUpdatesToBeForcedSoon
def thereAreUpdatesToBeForcedSoon(hours=72):
'''Return True if any updates need to be installed within the next
X hours, false otherwise'''
installinfo = getInstallInfo()
if installinfo:
now = NSDate.date()
now_xhours = NSDate.dateWithTimeIntervalSinceNow_(hours * 3600)
for item in installinfo.get('managed_installs', []):
force_install_after_date = item.get('force_install_after_date')
if force_install_after_date:
force_install_after_date = discardTimeZoneFromDate(
force_install_after_date)
if now_xhours >= force_install_after_date:
return True
return False
示例10: predicate_info_object
def predicate_info_object():
'''Returns our info object used for predicate comparisons'''
info_object = {}
machine = getMachineFacts()
info_object.update(machine)
info_object.update(get_conditions())
# use our start time for "current" date (if we have it)
# and add the timezone offset to it so we can compare
# UTC dates as though they were local dates.
info_object['date'] = add_tzoffset_to_date(
NSDate.dateWithString_(
reports.report.get('StartTime', reports.format_time())))
# split os version into components for easier predicate comparison
os_vers = machine['os_vers']
os_vers = os_vers + '.0.0'
info_object['os_vers_major'] = int(os_vers.split('.')[0])
info_object['os_vers_minor'] = int(os_vers.split('.')[1])
info_object['os_vers_patch'] = int(os_vers.split('.')[2])
# get last build number component for easier predicate comparison
build = machine['os_build_number']
info_object['os_build_last_component'] = pkgutils.MunkiLooseVersion(
build).version[-1]
if 'Book' in machine.get('machine_model', ''):
info_object['machine_type'] = 'laptop'
else:
info_object['machine_type'] = 'desktop'
return info_object
示例11: run
def run(config):
""" starts self-control with custom parameters, depending on the weekday and the config """
check_if_running(config["username"])
try:
schedule = next(s for s in config["block-schedules"] if is_schedule_active(s))
except StopIteration:
syslog.syslog(syslog.LOG_ALERT, "No schedule is active at the moment. Shutting down.")
exit(0)
duration = get_duration_minutes(schedule["end-hour"], schedule["end-minute"])
set_selfcontrol_setting("BlockDuration", duration, config["username"])
set_selfcontrol_setting("BlockAsWhitelist", 1 if schedule.get("block-as-whitelist", False) else 0,
config["username"])
if schedule.get("host-blacklist", None) is not None:
set_selfcontrol_setting("HostBlacklist", schedule["host-blacklist"], config["username"])
elif config.get("host-blacklist", None) is not None:
set_selfcontrol_setting("HostBlacklist", config["host-blacklist"], config["username"])
# In legacy mode manually set the BlockStartedDate, this should not be required anymore in future versions
# of SelfControl.
if config.get("legacy-mode", True):
set_selfcontrol_setting("BlockStartedDate", NSDate.date(), config["username"])
# Start SelfControl
subprocess.call(["{path}/Contents/MacOS/org.eyebeam.SelfControl".format(path=config["selfcontrol-path"]),
str(getpwnam(config["username"]).pw_uid),
"--install"])
syslog.syslog(syslog.LOG_ALERT, "SelfControl started for {min} minute(s).".format(min=duration))
示例12: _nestedRunLoopReaderUntilEOLchars_
def _nestedRunLoopReaderUntilEOLchars_(self, eolchars):
"""
This makes the baby jesus cry.
I want co-routines.
"""
app = NSApplication.sharedApplication()
window = self.textView.window()
self.setCharacterIndexForInput_(self.lengthOfTextView())
# change the color.. eh
self.textView.setTypingAttributes_(
{NSFontAttributeName: self.font(), NSForegroundColorAttributeName: self.codeColor()}
)
while True:
event = app.nextEventMatchingMask_untilDate_inMode_dequeue_(
NSUIntegerMax, NSDate.distantFuture(), NSDefaultRunLoopMode, True
)
if (event.type() == NSKeyDown) and (event.window() == window):
eol = event.characters()
if eol in eolchars:
break
app.sendEvent_(event)
cl = self.currentLine()
if eol == "\r":
self.writeCode_("\n")
return cl + eol
示例13: find_apps_in_dirs
def find_apps_in_dirs(dirlist):
"""Do spotlight search for type applications within the
list of directories provided. Returns a list of paths to applications
these appear to always be some form of unicode string.
"""
applist = []
query = NSMetadataQuery.alloc().init()
query.setPredicate_(
NSPredicate.predicateWithFormat_('(kMDItemKind = "Application")'))
query.setSearchScopes_(dirlist)
query.startQuery()
# Spotlight isGathering phase - this is the initial search. After the
# isGathering phase Spotlight keeps running returning live results from
# filesystem changes, we are not interested in that phase.
# Run for 0.3 seconds then check if isGathering has completed.
runtime = 0
maxruntime = 20
while query.isGathering() and runtime <= maxruntime:
runtime += 0.3
NSRunLoop.currentRunLoop(
).runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.3))
query.stopQuery()
if runtime >= maxruntime:
display.display_warning(
'Spotlight search for applications terminated due to excessive '
'time. Possible causes: Spotlight indexing is turned off for a '
'volume; Spotlight is reindexing a volume.')
for item in query.results():
pathname = item.valueForAttribute_('kMDItemPath')
if pathname and not is_excluded_filesystem(pathname):
applist.append(pathname)
return applist
示例14: notification
def notification(title, subtitle, message, data=None, sound=True):
"""
Notification sender. Apple says, "The userInfo content must be of reasonable serialized size (less than 1k) or an
exception will be thrown." So don't do that!
"""
if data is not None and not isinstance(data, Mapping):
raise TypeError('notification data must be a mapping')
notification = NSUserNotification.alloc().init()
notification.setTitle_(title)
notification.setSubtitle_(subtitle)
notification.setInformativeText_(message)
notification.setUserInfo_({} if data is None else data)
if sound:
notification.setSoundName_("NSUserNotificationDefaultSoundName")
notification.setDeliveryDate_(NSDate.dateWithTimeInterval_sinceDate_(0, NSDate.date()))
NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)
示例15: addPayloadFromPlistContents
def addPayloadFromPlistContents(self, plist_dict, domain, manage, is_byhost=False):
"""Add one plist dict contents to the profile's payloads. domain is the
preferences domain (ie. com.apple.finder), manage is one of 'Once', 'Often' or 'Always',
and is_byhost is a boolean representing whether the preference is to be used as a ByHost.
"""
payload_dict = {}
# Frequency to apply settings, or 'state'
if manage == 'Always':
state = 'Forced'
else:
state = 'Set-Once'
if is_byhost:
domain += '.ByHost'
# Yet another nested dict for the actual contents
payload_dict[domain] = {}
payload_dict[domain][state] = []
payload_dict[domain][state].append({})
payload_dict[domain][state][0]['mcx_preference_settings'] = plist_dict
# Add a datestamp if we're managing 'Once'
if manage == 'Once':
now = NSDate.new()
payload_dict[domain][state][0]['mcx_data_timestamp'] = now
self._addPayload(payload_dict)