本文整理汇总了Python中task.Task类的典型用法代码示例。如果您正苦于以下问题:Python Task类的具体用法?Python Task怎么用?Python Task使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Task类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: spawnImmediateTask
def spawnImmediateTask(self, jobid, taskid_complex=None, params=None):
'''
Run task immediately using basic configuration of job
@param jobid:int
@param taskid_complex: string
@param params: string
'''
job = Job.getByJobID(jobid)
if not job:
raise ValueError("Job(id:%d) is not existed or not enabled." % (jobid))
if params :
job.set_command(job._substituteReservedWord(params))
if taskid_complex:
task = Task(job.get_jobid(), uuid.uuid1().hex, datetime.now(),
job.getCommandToExcute(), job.get_retry(), job, job.get_depend(), taskid_complex)
else:
task = Task(job.get_jobid(), uuid.uuid1().hex, datetime.now(),
job.getCommandToExcute(), job.get_retry(), job, job.get_depend())
t = TaskRunner(0, task, self._status, self, params)
t.daemon = True
task.save()
self._status.add_waiting_task(task, t)
t.start()
return task
示例2: add_function
def add_function(subparsers, module, funcname):
func = getattr(module, funcname)
if getattr(func, 'ignore', False) or not inspect.isfunction(func):
return
depends = getattr(func, "depends", None)
task = Task(funcname, func, depends)
rules[funcname] = task
subparser = subparsers.add_parser(funcname, help=func.__doc__)
args, varargs, keywords, defaults = inspect.getargspec(func)
defaults = defaults or []
args = args or []
n_args = len(args) - len(defaults)
for arg in args[:n_args]:
subparser.add_argument(arg)
task.args.append(arg)
if varargs:
subparser.add_argument(varargs,
nargs="*")
task.varargs = varargs
for arg, default in zip(args[n_args:], defaults):
task.args.append(arg)
task.defaults[arg] = default
name = ('-' if len(arg) == 1 else '--') + arg
if isinstance(default, bool):
action = "store_" + str(not default).lower()
subparser.add_argument(name, default=default, action=action)
elif isinstance(default, int):
subparser.add_argument(name, default=default,
action="store", type=int)
else:
subparser.add_argument(name, default=default,
action="store")
示例3: __init__
def __init__(self, project, name):
Task.__init__(self)
Persistent.__init__(self, project.persistent, name)
self.name = name
self.fhs = FHS.shared(project)
project.option_collector.option_decls.add(self.__class__)
self.check_missing = project.options.get('check-missing', 'yes') != 'no'
示例4: compile_enb
def compile_enb(self, build_arguments, log_suffix=""):
log("INFO: ALU test: compile softmodem on " + self.enb_machine)
envcomp = list(self.env)
envcomp.append('BUILD_ARGUMENTS="' + build_arguments + '"')
#we don't care about BUILD_OUTPUT but required (TODO: change that)
envcomp.append('BUILD_OUTPUT=/')
logdir = self.logdir + "/compile_log"
remote_files = "'/tmp/oai_test_setup/oai/cmake_targets/log/*'"
post_action = "mkdir -p "+ logdir + \
" && sshpass -p " + self.oai_password + \
" scp -r " + self.oai_user + \
"@" + self.enb_machine + ":" + remote_files + " " + logdir + \
" || true"
task = Task("actions/compilation.bash",
"compile_softmodem",
self.enb_machine,
self.oai_user,
self.oai_password,
envcomp,
self.logdir + "/compile_softmodem." + log_suffix + \
self.enb_machine,
post_action=post_action)
ret = task.wait()
if ret != 0:
log("ERROR: softmodem compilation failure");
raise TestFailed()
task.postaction()
示例5: start_epc
def start_epc(self):
#launch HSS, wait for prompt
log("INFO: ALU test: run HSS")
self.task_hss = Task("actions/alu_hss.bash",
"alu_hss",
self.epc_machine,
self.oai_user,
self.oai_password,
self.env,
self.logdir + "/alu_hss." + self.epc_machine,
event=self.event)
self.task_hss.waitlog('S6AS_SIM-> ')
#then launch EPC, wait for connection on HSS side
log("INFO: ALU test: run EPC")
task_epc = Task("actions/alu_epc.bash",
"ALU EPC",
self.epc_machine,
self.oai_user,
self.oai_password,
self.env,
self.logdir + "/alu_epc." + self.epc_machine)
ret = task_epc.wait()
if ret != 0:
log("ERROR: EPC start failure");
raise TestFailed()
self.task_hss.waitlog('Connected\n')
示例6: __init__
def __init__(self, conf):
Task.__init__(self, conf)
self.name = "Nginx"
self.addRequiredFields(["base_dir", "domain_name", "nginx_template_url"])
self.packages = ["nginx"]
self.checkRequiredConf(conf)
示例7: get
def get(self, project, queue, task):
""" Get the named task in a queue.
Args:
project: A string containing an application ID.
queue: A string containing a queue name.
task: A string containing a task ID.
"""
task = Task({'id': task, 'queueName': queue})
requested_fields = self.get_argument('fields', None)
if requested_fields is None:
fields = TASK_FIELDS
else:
fields = parse_fields(requested_fields)
omit_payload = False
if 'payloadBase64' not in fields:
omit_payload = True
queue = self.queue_handler.get_queue(project, queue)
if queue is None:
write_error(self, HTTPCodes.NOT_FOUND, 'Queue not found.')
return
task = queue.get_task(task, omit_payload=omit_payload)
self.write(json.dumps(task.json_safe_dict(fields=fields)))
示例8: menu
def menu(arguments):
if arguments['list']:
if arguments['--recursive']:
task_lineage(arguments)
else:
task_list(arguments)
else:
try:
if arguments['create']:
Task.create(**_task_create_kwargs(arguments))
elif arguments['read']:
task_read(arguments)
elif arguments['set']:
task_set(arguments)
elif arguments['delete']:
Task(arguments['<name>']).delete()
elif arguments['reset']:
task_reset(arguments)
except NameError as exc:
print(PACKAGE_NAME, 'Error!', exc)
sys.exit(1)
示例9: read_tasks
def read_tasks(cls, infile):
tasks = []
default_tz = pytz.utc
for event, elem in etree.iterparse(infile, events=("start", "end")):
if event == "start":
if elem.tag == "defaults":
in_defaults = True
else:
# Stop reading as soon as the </tasks> tag is encountered.
if elem.tag == "tasks":
break
elif elem.tag == "defaults":
in_defaults = False
# Otherwise, parse each <task> element in accordance to the way
# it was output.
elif elem.tag == "task":
attrs = elem.attrib
# XXX When project of a task becomes something more than
# just a string, the code will probably break on the
# following line.
if "project" in attrs:
project = attrs["project"]
else:
project = ""
task = Task(name=elem.text, project=project, id=int(attrs["id"]))
if "done" in attrs:
task.done = bool(int(attrs["done"]))
if "time" in attrs:
task.time = cls._timedelta_fromrepr(attrs["time"])
if "deadline" in attrs:
task.deadline = cls._read_time(attrs, "deadline", default_tz=default_tz)
tasks.append(task)
elif elem.tag == "timezone" and in_defaults:
default_tz = pytz.timezone(elem.text)
return tasks
示例10: __init__
def __init__(self, message, hosts):
Task.__init__(self)
self.__message = message
self.__hosts = hosts
with database.transaction() as t:
t.execute("SELECT CURRENT_TIMESTAMP AT TIME ZONE 'UTC'")
(self.__batch_time,) = t.fetchone()
示例11: __init__
def __init__(self, url, path=None, overwrite=False, **kwargs):
Task.__init__(self)
self.url = url
self.path = path
self.overwrite = overwrite
self.kwargs = kwargs
self.size = 0
示例12: ffmpeg
def ffmpeg(arg):
torun = Task(createfrom=arg)
# Get the output file extension:
destExtension = torun.outfile.split(".")[-1]
print torun.outfile.split(".")
tmpfile = "tmp." + destExtension
codeccheck = subprocess.Popen(["ffmpeg", "-codecs"], stdout=subprocess.PIPE)
allcodecs = codeccheck.communicate()[0]
if allcodecs.find("libfdk_aac") == -1:
print "Install libfdk_aac for better audio quality!"
if torun.forcefdk == True:
print "Server has disabled workers without libfdk_aac!"
sys.exit()
else:
if "libfdk_aac" in torun.arguments:
libfdk_pos = torun.arguments.index("libfdk_aac")
torun.arguments[libfdk_pos] = "aac"
torun.arguments.append("-strict")
torun.arguments.append("-2")
out=subprocess.call(["ffmpeg","-i", torun.infile]+torun.arguments+[tmpfile])
if not out == 0:
print "FFMPEG FAILED"
else:
shutil.move(tmpfile,torun.outfile)
os.remove(torun.infile)
try:
os.remove(tmpfile)
except:
pass
示例13: __init__
def __init__(self, conf):
Task.__init__(self,conf)
self.name = 'Django Install'
self.addRequiredFields(['django_url','base_dir','domain_name'])
self.packages = ['cron','python-mysqldb']
self.checkRequiredConf(conf)
示例14: create_valid_task
def create_valid_task():
unit_id = "3c82ef61-0875-41d3-99ba-101672d79d6b"
task_id = uuid.uuid4().hex
valid_json_dict = {
"title": "Blank",
"task_id": task_id,
"chronicle": [
{
"time_ms": 0.3,
"unit_id": unit_id,
"hop": 1
}
],
"from_unit": unit_id,
"to_unit": "a789ada1-edb5-4cfe-b1f9-8584abbf8a2f",
"command": {
"announce": {}
},
"response": {}
}
valid_command = Task(unit_id, **valid_json_dict)
valid_response = Task(unit_id, **valid_json_dict)
valid_response.add_response(response = {"response":"yes"})
return valid_command, valid_response
示例15: __init__
def __init__(self, robot, link, target, **kwargs):
if hasattr(target, 'robot_link'): # used for ROS communications
target.robot_link = link.index # dirty
elif type(target) is list:
target = array(target)
def _pos_residual(target_pose):
residual = target_pose - link.pose
if dot(residual[0:4], residual[0:4]) > 1.:
return _oppose_quat * target_pose - link.pose
return residual
if hasattr(target, 'pose'):
def pos_residual():
return _pos_residual(target.pose)
elif type(target) is ndarray:
def pos_residual():
return _pos_residual(target)
else: # link frame target should be a pose
raise Exception("Target %s has no 'pose' attribute" % type(target))
def jacobian():
return robot.compute_link_pose_jacobian(link)
self.link = link
Task.__init__(self, jacobian, pos_residual=pos_residual, **kwargs)