本文整理汇总了Python中cmd3.console.Console类的典型用法代码示例。如果您正苦于以下问题:Python Console类的具体用法?Python Console怎么用?Python Console使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Console类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: info
def info(self):
# TODO: implement self. dbath, self.port, self.logpath
Console.ok("Mongo parameters")
Console.ok(" dbpath: {:}".format(self.db_path))
Console.ok(" port: {:}".format(self.port))
Console.ok(" logfile: {:}".format(self.log_file))
Console.ok(" dbname: {:}".format(self.dbname))
示例2: _print_default
def _print_default(self, attr=None):
to_print = self.get_defaults()
columns = None
if attr:
columns = [attr]
elif self.arguments['--column'] and self.arguments['--column'] != "all":
columns = [x.strip() for x in self.arguments['--column'].split(',')]
# ----------------------------------
# flexible input
for index, item in enumerate(columns):
if item in ['format']:
columns[index] = "shell_print_format"
# ----------------------------------
if self.arguments['--format']:
if self.arguments['--format'] not in ['table', 'json', 'csv']:
Console.error("please select printing format among table, json and csv")
return
else:
p_format = self.arguments['--format']
else:
p_format = None
# if p_format == 'table' or p_format is None:
# print(row_table(to_print, order=None, labels=["Default", "Value"]))
# else:
shell_commands_dict_output(self.username,
to_print,
print_format=p_format,
header=columns,
oneitem=True,
vertical_table=True)
示例3: display
def display(cls, user_dicts=None, user_name=None):
if bool(user_dicts):
values = []
table = Texttable(max_width=180)
for entry in user_dicts:
items = []
headers = []
for key, value in entry.iteritems():
if key == "projects":
project_entry = ""
if value:
for itm in value:
user_project = Project.objects(id=ObjectId(itm.get('$oid'))).only('title',
'project_id').first()
project_entry = project_entry + user_project.title + ", "
items.append(project_entry)
elif key == "roles":
role_entry = ""
if value:
for itm in value:
role_entry = role_entry+itm + ", "
role_entry = role_entry.rstrip(', ')
items.append(role_entry)
else:
items.append(value)
headers.append(key.replace('_', ' ').title())
values.append(items)
table.add_row(items)
table.header(headers)
print table.draw()
else:
if user_name:
Console.error("No user in the system with name '{0}'".format(user_name))
示例4: add
def add(self, job):
"""
job is a dictionary. One of its attributes is 'name'.
The element is inserted into the db with the id 'name'
:param job: the job to be added
:return:
"""
matchingJobs = self.find_jobs("job_name", job["job_name"])
# A job with this job name already exists
if matchingJobs.count() != 0:
Console.error("A job with this job name already exists in the database")
# A job with this job name does not exist so insert it
else:
# Set the ID of this job to be the job name
job["_id"] = job["job_name"]
# Set the update time
update = str(datetime.datetime.now())
job["update_time"] = update
# Save the job object
if self.database is not None:
db_job_object = self.jobs.save(job)
return db_job_object
示例5: load_plugins
def load_plugins(classprefix, plugin_list):
"""
loads the plugins specified in the list
:param classprefix: the class prefix
:param plugin_list: the list of plugins
"""
# classprefix "cmd3.plugins."
plugins = []
import_object = {}
# log.info(str(list))
for plugin in plugin_list:
if cygwin:
plugin = path_into_cygpath(plugin)
# print ("PPPPP", classprefix, plugin)
try:
import_object[plugin] = __import__(
classprefix + "." + plugin, globals(), locals(), [plugin], -1)
# print ("TTT", import_object[plugin], type(import_object[plugin]))
load_module = "cls = import_object['{0}'].{1}".format(plugin, plugin)
# print ("LLL", load_module)
exec(load_module)
plugins.append(cls)
except Exception, e:
# if echo:
Console.error("loading module {0} {1}".format(str(plugin), str(classprefix)))
Console.error(70 * "=")
print(e)
Console.error(70 * "=")
print(traceback.format_exc())
Console.error(70 * "-")
print(sys.exc_info()[0])
Console.error(70 * "-")
示例6: display_json
def display_json(cls, project_dict=None, project_id=None):
if bool(project_dict):
# pprint.pprint(user_json)
print json.dumps(project_dict, indent=4)
else:
if project_id:
Console.error("No project in the system with name '{0}'".format(project_id))
示例7: get_working_cloud_name
def get_working_cloud_name(self):
'''
get the name of a cloud to be work on, if CLOUD not given, will pick the
slected cloud, is --all, will return a list of active clouds
'''
self.cloudmanage._connect_to_mongo()
activeclouds = None
try:
activeclouds = self.cloudmanage.mongo.active_clouds(self.username)
except:
pass
if self.arguments['--all']:
if activeclouds is None:
print("no active cloud, please activate a cloud by 'cloud on [CLOUD]'")
return False
return activeclouds
else:
if self.arguments['CLOUD']:
name = self.arguments['CLOUD']
else:
name = self.cloudmanage.get_selected_cloud(self.username)
if self.cloudmanage.get_clouds(self.username, getone=True, cloudname=name) is None:
Console.error(
"no cloud information of '{0}' in database".format(name))
return False
if name not in activeclouds:
Console.warning(
"cloud '{0}' is not active, to activate a cloud: cloud on [CLOUD]".format(name))
return False
return [name]
示例8: do_spark
def do_spark(self, args, arguments):
"""
::
Usage:
spark NAME
spark deploy HOST
tests via ping if the host ith the give NAME is reachable
Arguments:
NAME Name of the machine to test
Options:
-v verbose mode
"""
pprint(arguments)
if arguments["deploy"]:
Console.ok("I want to deploy")
host = arguments["HOST"]
print(host)
elif arguments["NAME"] is None:
Console.error("Please specify a host name")
else:
host = arguments["NAME"]
Console.info("trying to reach {0}".format(host))
status = command_spark.status(host)
if status:
Console.info("machine " + host + " has been found. ok.")
else:
Console.error("machine " + host + " not reachable. error.")
pass
示例9: create_user_from_file
def create_user_from_file(cls, file_path):
try:
filename = path_expand(file_path)
file_config = ConfigDict(filename=filename)
except:
Console.error("Could not load file, please check filename and its path")
return
try:
user_config = file_config.get("cloudmesh", "user")
user_name = user_config['username']
user = User()
update_document(user, user_config)
except:
Console.error("Could not get user information from yaml file, "
"please check you yaml file, users information must be "
"under 'cloudmesh' -> 'users' -> user1...")
return
try:
if cls.check_exists(user_name) is False:
cls.add(user)
Console.info("User created in the database.")
else:
Console.error("User with user name " + user_name + " already exists.")
return
except:
Console.error("User creation in database failed, " + str(sys.exc_info()))
return
示例10: set_password
def set_password(cls, user_name, passwd):
pass_hash = sha256_crypt.encrypt(passwd)
try:
User.objects(username=user_name).update_one(set__password=pass_hash)
Console.info("User password updated.")
except:
Console.error("Oops! Something went wrong while trying to set user password")
示例11: get_working_cloud_name
def get_working_cloud_name(self):
'''
get the name of a cloud to work on, if CLOUD not given, will pick the
selected or default cloud
'''
cloudname = None
cloudobj = CloudManage()
mongo = cm_mongo()
if self.arguments['--cloud']:
cloud = cloudobj.get_clouds(
self.username, getone=True, cloudname=self.arguments['--cloud'])
if cloud is None:
Console.error(
"could not find cloud '{0}'".format(self.arguments['--cloud']))
return False
else:
cloudname = self.arguments['--cloud']
else:
cloudname = cloudobj.get_selected_cloud(self.username)
if cloudname not in mongo.active_clouds(self.username):
Console.warning(
"cloud '{0}' is not active, to activate a cloud: cloud on [CLOUD]".format(cloudname))
return False
else:
return cloudname
示例12: _default_format
def _default_format(self):
self._start_cm_user()
defaults_data = self.user_obj.info(self.username)['defaults']
if self.arguments['VALUE']:
allowed_formats = ['table', 'json', 'csv']
if self.arguments['VALUE'] not in allowed_formats:
Console.warning("allowed formats are {0}".format(str(allowed_formats)))
return
else:
defaults_data['shell_print_format'] = self.arguments['VALUE']
self.user_obj.set_defaults(self.username, defaults_data)
Console.ok("set '{0}' as default print format".format(self.arguments['VALUE']))
else:
format = None
try:
format = defaults_data['shell_print_format']
except:
pass
if format not in [None, 'none']:
print(defaults_data['shell_print_format'])
else:
defaults_data['shell_print_format'] = "table"
self.user_obj.set_defaults(self.username, defaults_data)
defaults_data = self.user_obj.info(self.username)
print(defaults_data['shell_print_format'])
示例13: set_project_status
def set_project_status(cls, project_id, status):
if project_id:
try:
Project.objects(project_id=project_id).update_one(set__status=status)
except:
Console.error("Oops! Something went wrong while trying to amend project status")
else:
Console.error("Please specify the project to be amended")
示例14: get_cloud_name
def get_cloud_name(self, cm_user_id):
"""Returns a default cloud name if exists
"""
try:
return self.cm_user.get_defaults(cm_user_id)['cloud']
except KeyError:
Console.error('Please set a default cloud.')
return None
示例15: _list_project
def _list_project(self):
self.cloudmanage._connect_to_mongo()
selected_project = None
try:
selected_project = self.cloudmanage.mongo.db_defaults.find_one(
{'cm_user_id': self.username + "OIO"})['project']
except Exception, NoneType:
Console.warning("could not find selected project in the database")