本文整理汇总了Python中workflow.background.is_running函数的典型用法代码示例。如果您正苦于以下问题:Python is_running函数的具体用法?Python is_running怎么用?Python is_running使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了is_running函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_workflow_update_methods
def test_workflow_update_methods(self):
"""Workflow update methods"""
def fake(wf):
return
Workflow().reset()
# Initialise with outdated version
wf = Workflow(update_settings={
'github_slug': 'deanishe/alfred-workflow-dummy',
'version': 'v2.0',
'frequency': 1,
})
wf.run(fake)
# Check won't have completed yet
self.assertFalse(wf.update_available)
# wait for background update check
self.assertTrue(is_running('__workflow_update_check'))
while is_running('__workflow_update_check'):
time.sleep(0.05)
time.sleep(1)
# There *is* a newer version in the repo
self.assertTrue(wf.update_available)
# Mock out subprocess and check the correct command is run
c = WorkflowMock()
with c:
self.assertTrue(wf.start_update())
# wf.logger.debug('start_update : {}'.format(c.cmd))
self.assertEquals(c.cmd[0], '/usr/bin/python')
self.assertEquals(c.cmd[2], '__workflow_update_install')
# Grab the updated release data, then reset the cache
update_info = wf.cached_data('__workflow_update_status')
wf.reset()
# Initialise with latest available release
wf = Workflow(update_settings={
'github_slug': 'deanishe/alfred-workflow-dummy',
'version': update_info['version'],
})
wf.run(fake)
# Wait for background update check
self.assertTrue(is_running('__workflow_update_check'))
while is_running('__workflow_update_check'):
time.sleep(0.05)
# Remote version is same as the one we passed to Workflow
self.assertFalse(wf.update_available)
self.assertFalse(wf.start_update())
示例2: test_kill
def test_kill(self):
"""Kill"""
assert kill('test') is False
cmd = ['sleep', '1']
assert run_in_background('test', cmd) == 0
assert is_running('test')
assert kill('test') is True
sleep(0.3) # give process time to exit
assert not is_running('test')
示例3: test_run_in_background
def test_run_in_background(self):
"""Run in background"""
cmd = ['sleep', '1']
assert run_in_background('test', cmd) == 0
assert is_running('test')
assert os.path.exists(_pidfile('test'))
# Already running
assert run_in_background('test', cmd) is None
sleep(1.1) # wait for job to finish
assert not is_running('test')
assert not os.path.exists(_pidfile('test'))
示例4: test_run_in_background
def test_run_in_background(self):
"""Run in background"""
cmd = ['sleep', '1']
run_in_background('test', cmd)
sleep(0.5)
self.assertTrue(is_running('test'))
self.assertTrue(os.path.exists(self._pidfile('test')))
self.assertEqual(run_in_background('test', cmd), None)
sleep(0.6)
self.assertFalse(is_running('test'))
self.assertFalse(os.path.exists(self._pidfile('test')))
示例5: test_existing_process
def test_existing_process(self):
"""Existing process"""
_write_pidfile('test', os.getpid())
try:
assert is_running('test')
assert os.path.exists(_pidfile('test'))
finally:
_delete_pidfile('test')
示例6: main
def main(wf):
"""Run workflow Script Filter.
Args:
wf (workflow.Workflow): Current Workflow object.
"""
global ureg
ureg = UnitRegistry(wf.decode(DEFAULT_UNIT_DEFINITIONS))
ureg.default_format = 'P'
wf.magic_arguments['appkey'] = open_currency_instructions
if not len(wf.args):
return
query = wf.args[0] # .lower()
log.debug('query : %s', query)
handle_update(wf)
# Create data files if necessary
bootstrap(wf)
# Add workflow and user units to unit registry
register_units()
# Notify of available update
if wf.update_available:
wf.add_item('A newer version is available',
'Action this item to download & install the new version',
autocomplete='workflow:update',
icon=ICON_UPDATE)
# Load cached data
exchange_rates = wf.cached_data(CURRENCY_CACHE_NAME, max_age=0)
if exchange_rates: # Add exchange rates to conversion database
register_exchange_rates(exchange_rates)
if not wf.cached_data_fresh(CURRENCY_CACHE_NAME, CURRENCY_CACHE_AGE):
# Update currency rates
cmd = ['/usr/bin/python', wf.workflowfile('currency.py')]
run_in_background('update', cmd)
wf.rerun = 0.5
if is_running('update'):
wf.rerun = 0.5
if exchange_rates is None: # No data cached yet
wf.add_item(u'Fetching exchange rates…',
'Currency conversions will be momentarily possible',
icon=ICON_INFO)
else:
wf.add_item(u'Updating exchange rates…',
icon=ICON_INFO)
return convert(query)
示例7: generate_all_icons
def generate_all_icons():
"""Callback for magic argument"""
if background.is_running('icongen'):
return 'Generation already in progress.'
background.run_in_background(
'icongen',
['/usr/bin/python', wf.workflowfile('icons.py')]
)
return 'Starting icon generation. This may take up to 15 minutes.'
示例8: run
def run(self, wf):
from docopt import docopt
self.wf = wf
args = docopt(__usage__, argv=self.wf.args)
self.workflows = self.wf.cached_data('workflows', None,
max_age=0)
if self.workflows:
log.debug('%d workflows in cache', len(self.workflows))
else:
log.debug('0 workflows in cache')
# Start update scripts if cached data is too old
if not self.wf.cached_data_fresh('workflows',
max_age=CACHE_MAXAGE):
self._update()
# Notify user if cache is being updated
if is_running('update'):
self.wf.add_item('Updating from Packal…',
'Please try again in a second or two',
valid=False, icon=ICON_INFO)
if not self.workflows:
self.wf.send_feedback()
return 0
self.workflows.sort(key=itemgetter('updated'), reverse=True)
log.debug('%d workflows found in cache', len(self.workflows))
self.query = args.get('<query>')
self.author = args.get('<author>')
self.bundleid = args.get('<bundleid>')
for key in ('tags', 'categories', 'versions', 'authors'):
if args.get(key):
return self._two_stage_filter(key)
if args.get('author-workflows'):
return self.do_author_workflows()
elif args.get('workflows'):
return self._filter_workflows(self.workflows, self.query)
elif args.get('update'):
return self.do_update()
elif args.get('open'):
return self.do_open()
elif args.get('status'):
return self.do_status()
elif args.get('ignore-author'):
return self.do_ignore_author()
else:
raise ValueError('No action specified')
示例9: do_import_search
def do_import_search(wf, url):
"""Parse URL for OpenSearch config."""
ctx = Context(wf)
# ICON_IMPORT = ctx.icon('import')
ICONS_PROGRESS = [
ctx.icon('progress-1'),
ctx.icon('progress-2'),
ctx.icon('progress-3'),
ctx.icon('progress-4'),
]
data = wf.cached_data('import', None, max_age=0, session=True)
if data:
error = data['error']
search = data['search']
# Clear cache data
wf.cache_data('import', None, session=True)
wf.cache_data('import-status', None, session=True)
if error:
wf.add_item(error, icon=ICON_ERROR)
wf.send_feedback()
return
it = wf.add_item(u'Add "{}"'.format(search['name']),
u'↩ to add search',
valid=True,
icon=search['icon'])
for k, v in search.items():
it.setvar(k, v)
else:
progress = int(os.getenv('progress') or '0')
i = progress % len(ICONS_PROGRESS)
picon = ICONS_PROGRESS[i]
log.debug('progress=%d, i=%d, picon=%s', progress, i, picon)
wf.setvar('progress', progress + 1)
if not is_running('import'):
run_in_background('import', ['./searchio', 'fetch', url])
status = wf.cached_data('import-status', None, max_age=0, session=True)
title = status or u'Fetching OpenSearch Configuration …'
wf.rerun = 0.2
wf.add_item(title,
u'Results will be shown momentarily',
icon=picon)
wf.send_feedback()
示例10: main
def main(wf):
args = Args(wf.args)
actions = wf.cached_data('actions', None, max_age=0)
if wf.update_available:
# Add a notification to top of Script Filter results
wf.add_item(u'New version available',
u'Action this item to install the update',
autocomplete='workflow:update',
icon=ICON_INFO)
if not wf.cached_data_fresh('actions', max_age=CACHE_MAX_AGE):
cmd = ['/usr/bin/python', wf.workflowfile('alfredhelp.py'), '--scan']
run_in_background(u'scan', cmd)
if is_running(u'scan'):
wf.add_item(
title=u'Scanning alfred workflows...',
valid=False,
icon=ICON_INFO
)
if args.show_keywords and actions:
if args.query:
actions = wf.filter(args.query, actions, key=search_key)
for action in actions:
argument = action.keyword
if action.add_space:
argument += u' '
wf.add_item(
title=u'{keyword} - {title}'.format(keyword=action.keyword, title=action.title),
subtitle=action.subtitle,
icon=action.icon,
arg=argument,
valid=True
)
elif args.scan:
def get_posts():
return scan(path.join(wf.alfred_env['preferences'], 'workflows'))
wf.cached_data('actions', get_posts, max_age=CACHE_MAX_AGE)
scan(path.join(wf.alfred_env['preferences'], 'workflows'))
wf.send_feedback()
return 0
示例11: output_query_vault_results
def output_query_vault_results(ap):
"""
A simple helper function to manage outputting LastPass vault items to an
Alfred Script Filter. Uses an ArgParser instance to figure out which
command and argument to use.
"""
# Notify the user if the cache is being updated:
if is_running('update'):
log.debug('Currenly running update; notifying user...')
wf.add_item(
'Getting new data from LastPass.',
'This should only take a few moments, so hang tight.',
valid=False,
icon='icons/loading.png',
uid='1'
)
results = util.search_vault_for_query(ap.arg)
if results:
for result in results:
wf.add_item(
result['hostname'],
'TAB to explore; ' +
'ENTER to copy password; ' +
'\u2318-Click to copy username; ' +
'Shift-Click to open URL',
modifier_subtitles={
'cmd': '\u2318-Click to copy username.',
'shift': 'Shift-Click to open the URL.'
},
valid=True,
arg='{} {}***{}'.format(ap.command,
result['hostname'],
result['url']),
autocomplete='view-details {}'.format(result['hostname']),
)
else:
wf.add_item(
'No items matching "{}".'.format(ap.arg),
'View the `lpvs` debug log for more information.',
valid=False,
icon='icons/warning.png'
)
wf.send_feedback()
return
示例12: main
def main(workflow):
parser = argparse.ArgumentParser()
parser.add_argument("--set-token", dest="api_token", nargs="?", default=None)
parser.add_argument("query", nargs="?", default=None)
arguments = parser.parse_args(workflow.args)
if arguments.api_token:
workflow.save_password("hipchat_api_token", arguments.api_token)
return 0
try:
api_token = workflow.get_password("hipchat_api_token")
except PasswordNotFound:
workflow.add_item(
"No API key set.", "Please use hcsettoken to set your Hipchat API token.", valid=False, icon=ICON_WARNING
)
workflow.send_feedback()
return 0
users = workflow.cached_data("users", None, max_age=0)
if not workflow.cached_data_fresh("users", max_age=60): # 60s
cmd = ["/usr/bin/python", workflow.workflowfile("update.py")]
run_in_background("update", cmd)
if is_running("update"):
logger.debug("updating users")
if arguments.query and users:
users = workflow.filter(arguments.query, users, key=search_terms_for_user, min_score=20)
if not users:
workflow.add_item("Whoops, no users found", icon=ICON_WARNING)
workflow.send_feedback()
return 0
for user in users:
status_icon = get_status_icon(user["presence"]["show"] if user["presence"] else None)
workflow.add_item(
user["name"], user["email"], arg=actionTemplate.format(user["mention_name"]), valid=True, icon=status_icon
)
workflow.send_feedback()
logger.debug("returned {} results".format(len(users)))
示例13: run
def run(self, wf):
"""Run workflow."""
self.wf = wf
wf.args # check for magic args
self.keyword = self.wf.settings.get('keyword', DEFAULT_KEYWORD)
args = docopt(__doc__)
log.debug(u'args : %r', args)
# Open Help file
if args.get('--helpfile'):
return self.do_open_help_file()
# Perform search
self.query = wf.decode(args.get('<query>') or '')
# List Smart Folders with custom keywords
if args.get('--config'):
return self.do_configure_folders()
# Was a configured folder passed?
folder = wf.decode(args.get('--folder') or '')
# Get list of Smart Folders. Update in background if necessary.
self.folders = self.wf.cached_data('folders', max_age=0)
if self.folders is None:
self.folders = []
# Update folder list if it's old
if not self.wf.cached_data_fresh('folders', CACHE_AGE_FOLDERS):
log.debug('updating list of Smart Folders in background...')
run_in_background('folders',
['/usr/bin/python',
self.wf.workflowfile('cache.py')])
if is_running('folders'):
self.wf.rerun = 0.5
# Has a specific folder been specified?
if folder:
return self.do_search_in_folder(folder)
return self.do_search_folders()
示例14: build_wf_entry
def build_wf_entry(wf):
if is_running('bg'):
"""Update status"""
phase = wf.stored_data('phase')
log.info('PHASE: ', phase)
if phase != 'done':
wf.rerun = 0.5
if phase == 'downloading':
pct = None
while pct is None:
try:
pct = wf.stored_data('download_percent')
except:
pass
progress = wf.stored_data('download_progress')
file = wf.stored_data('download_file')
# wf.rerun = 0.5
title = "Downloading {} [{}]".format(file, progress)
subtitle = string_from_percent(pct) + " " + str(pct) + "%"
wf.add_item(title, subtitle=subtitle)
if phase == 'processing':
try:
emoji_count = wf.stored_data('emoji_count')
subtitle = "Parsed {} emoji".format(emoji_count)
except:
subtitle = "Parsed ... emoji"
pass
title = 'Parsing Emoji'
wf.add_item(title, subtitle=subtitle)
else:
"""Last case"""
wf.add_item("Complete", subtitle='Emoji searching is now ready to use',
icon="images/Checkmark.png")
示例15: main
def main(wf):
# Workflow requires a query
query = wf.args[0]
index_exists = True
# Create index if it doesn't exist
if not os.path.exists(INDEX_DB):
index_exists = False
run_in_background('indexer', ['/usr/bin/python', 'index.py'])
# Can't search without an index. Inform user and exit
if not index_exists:
wf.add_item('Creating search index…', 'Please wait a moment',
icon=ICON_INFO)
wf.send_feedback()
return
# Inform user of update in case they're looking for something
# recently added (and it isn't there)
if is_running('indexer'):
wf.add_item('Updating search index…',
'Fresher results will be available shortly',
icon=ICON_INFO)
# Search!
start = time()
db = sqlite3.connect(INDEX_DB)
# Set ranking function with weightings for each column.
# `make_rank_function` must be called with a tuple/list of the same
# length as the number of columns "selected" from the database.
# In this case, `url` is set to 0 because we don't want to search on
# that column
db.create_function('rank', 1, make_rank_func((1.0, 1.0, 0)))
cursor = db.cursor()
try:
cursor.execute("""SELECT author, title, url FROM
(SELECT rank(matchinfo(books))
AS r, author, title, url
FROM books WHERE books MATCH ?)
ORDER BY r DESC LIMIT 100""", (query,))
results = cursor.fetchall()
except sqlite3.OperationalError as err:
# If the query is invalid, show an appropriate warning and exit
if b'malformed MATCH' in err.message:
wf.add_item('Invalid query', icon=ICON_WARNING)
wf.send_feedback()
return
# Otherwise raise error for Workflow to catch and log
else:
raise err
if not results:
wf.add_item('No matches', 'Try a different query', icon=ICON_WARNING)
log.info('{} results for `{}` in {:0.3f} seconds'.format(
len(results), query, time() - start))
# Output results to Alfred
for (author, title, url) in results:
wf.add_item(title, author, valid=True, arg=url, icon='icon.png')
wf.send_feedback()