本文整理汇总了Python中cli.CLI类的典型用法代码示例。如果您正苦于以下问题:Python CLI类的具体用法?Python CLI怎么用?Python CLI使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CLI类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MySQL
class MySQL(object):
def __init__(self, config=None, mysql_driver=MySQLdb):
self.__cli = CLI()
self.__mysql_driver = mysql_driver
self.__mysql_host = config.get("db_host")
self.__mysql_user = config.get("db_user")
self.__mysql_passwd = config.get("db_password")
self.__mysql_db = config.get("db_name")
self.__version_table = config.get("db_version_table")
if config.get("drop_db_first"):
self._drop_database()
self._create_database_if_not_exists()
self._create_version_table_if_not_exists()
def __mysql_connect(self, connect_using_db_name=True):
try:
conn = self.__mysql_driver.connect(host=self.__mysql_host, user=self.__mysql_user, passwd=self.__mysql_passwd)
# this should be configured in the config file, not hardcoded
conn.set_character_set('utf8')
if connect_using_db_name:
conn.select_db(self.__mysql_db)
return conn
except Exception, e:
self.__cli.error_and_exit("could not connect to database (%s)" % e)
示例2: _drop_database
def _drop_database(self):
sql = """\
SELECT 'DROP PUBLIC SYNONYM ' || SYNONYM_NAME ||';' FROM ALL_SYNONYMS \
WHERE OWNER = 'PUBLIC' AND TABLE_OWNER = '%s' \
UNION ALL \
SELECT 'DROP SYNONYM ' || SYNONYM_NAME ||';' FROM ALL_SYNONYMS \
WHERE OWNER = '%s' AND TABLE_OWNER = '%s' \
UNION ALL \
SELECT 'DROP ' || OBJECT_TYPE || ' ' || OBJECT_NAME ||';' FROM USER_OBJECTS \
WHERE OBJECT_TYPE <> 'TABLE' AND OBJECT_TYPE <> 'INDEX' AND \
OBJECT_TYPE<>'TRIGGER' AND OBJECT_TYPE<>'LOB' \
UNION ALL \
SELECT 'DROP ' || OBJECT_TYPE || ' ' || OBJECT_NAME ||' CASCADE CONSTRAINTS;' FROM USER_OBJECTS \
WHERE OBJECT_TYPE = 'TABLE' AND OBJECT_NAME NOT LIKE 'BIN$%%'""" % (self.__user.upper(), self.__user.upper(), self.__user.upper())
conn = self.__connect()
cursor = conn.cursor()
try:
cursor.execute(sql)
rows = cursor.fetchall()
failed_sqls = ''
for row in rows:
drop_sql = row[0]
try:
self.__execute(drop_sql)
except Exception, e:
failed_sqls = failed_sqls + "can't execute drop command '%s' in database '%s', %s\n" % (drop_sql, self.__db, str(e).strip())
if failed_sqls != '':
CLI.msg('\nThe following drop commands failed:\n%s' % (failed_sqls), "RED")
CLI.msg('\nDo you want to continue anyway (y/N):', "END")
to_continue = self.std_in.readline().strip()
if to_continue.upper() != 'Y':
raise Exception("can't drop database '%s'" % (self.__db) )
示例3: MSSQL
class MSSQL(object):
def __init__(self, config=None, mssql_driver=_mssql):
self.__cli = CLI()
self.__mssql_driver = mssql_driver
self.__mssql_host = config.get("db_host")
self.__mssql_user = config.get("db_user")
self.__mssql_passwd = config.get("db_password")
self.__mssql_db = config.get("db_name")
self.__version_table = config.get("db_version_table")
if config.get("drop_db_first"):
self._drop_database()
self._create_database_if_not_exists()
self._create_version_table_if_not_exists()
def __mssql_connect(self, connect_using_db_name=True):
try:
conn = self.__mssql_driver.connect(server=self.__mssql_host, user=self.__mssql_user, password=self.__mssql_passwd)
if connect_using_db_name:
conn.select_db(self.__mssql_db)
return conn
except Exception, e:
self.__cli.error_and_exit("could not connect to database (%s)" % e)
示例4: Config
class Config(object):
def __repr__(self):
return str(self.__config)
def __init__(self, config_file="simple-db-migrate.conf"):
self.__cli = CLI()
self.__config = {}
# read configurations
try:
f = codecs.open(config_file, "r", "utf-8")
exec(f.read())
except IOError:
self.__cli.error_and_exit("%s: file not found" % config_file)
else:
f.close()
try:
self.put("db_host", HOST)
self.put("db_user", USERNAME)
self.put("db_password", PASSWORD)
self.put("db_name", DATABASE)
self.put("db_version_table", "__db_version__")
migrations_dir = self.__get_migrations_absolute_dir(config_file, MIGRATIONS_DIR)
self.put("migrations_dir", migrations_dir)
except NameError, e:
self.__cli.error_and_exit("config file error: " + str(e))
示例5: main
def main():
f = open("food_diary.json", 'r')
try:
data = json.load(f)
except:
data = {}
c = open('calories.json', 'r')
try:
calories = json.load(c)
except:
calories = {}
f.close()
c.close()
cal = Calories(calories)
fd = FoodDiary(data, cal)
cli = CLI(fd)
cli.start()
f = open("food_diary.json", 'w')
json.dump(data, f, indent=4)
f.close()
c = open("calories.json", 'w')
json.dump(calories, c, indent=4)
c.close()
示例6: Hip
class Hip(object):
def __init__(self):
self.sms = Sms()
def run(self):
commands = ["inspire"]
self.cli = CLI(self.process, commands)
print self.cli.process()
def process(self, *args):
args = list(args)
cmd = args.pop(0)
if cmd == "inspire":
self.inspire()
else:
raise HipError("Unrecognized command: %s" % cmd)
def inspire(self):
inspiration = Inspiration()
quote = inspiration.getNext()
print quote["quote"].encode("ascii", "replace")
for soul in Folks().getActive():
phone = soul["phonenumber"]
print phone
self.sms.send(phone, quote["quote"])
inspiration.setSentDate(quote["id"], datetime.now())
示例7: _migrate
def _migrate(self):
""" Execute migrations based on git tags """
source = 'git'
current_ontology = None
current_version, origen = self.virtuoso.get_current_version()
# Making the first migration to the database
if current_version is None:
if self.config.get("file_migration", None) is not None:
self._execution_log(("- Current version is: %s" %
current_version),
"GREEN",
log_level_limit=1)
self._execution_log(("- Destination version is: %s" %
self.config.get("file_migration")),
"GREEN",
log_level_limit=1)
CLI.error_and_exit("Can't execute migration FROM None TO File "
"(TIP: version it using git --tag and then "
"use -m)")
else:
if origen == "file":
if self.config.get("file_migration", None) is not None:
self._execution_log(("- Current version is: %s" %
current_version),
"GREEN",
log_level_limit=1)
self._execution_log(("- Destination version is: %s" %
self.config.get("file_migration")),
"GREEN",
log_level_limit=1)
CLI.error_and_exit("Can't execute migration FROM File TO "
"File (TIP: version it using git --tag "
"and then use -m)")
current_ontology = self.virtuoso.get_ontology_by_version(
current_version)
if self.config.get("file_migration", None) is not None:
source = 'file'
destination_version = self.config.get("file_migration")
destination_ontology = self.virtuoso.get_ontology_from_file(
destination_version)
else:
destination_version = self._get_destination_version()
destination_ontology = self.virtuoso.get_ontology_by_version(
destination_version)
sparql_up, sparql_down = self.virtuoso.get_sparql(current_ontology,
destination_ontology,
current_version,
destination_version,
source)
self._execute_migrations(sparql_up,
sparql_down,
current_version,
destination_version)
示例8: main
def main():
# resolving the '-' issue
readline.set_completer_delims(readline.get_completer_delims().replace('-', ''))
cli = CLI()
if len(sys.argv) > 1:
try:
cli.onecmd(' '.join(sys.argv[1:]))
except BadResponseError as e:
print(str(e))
else:
prompt_for_credentials()
cli.cmdloop()
示例9: _verify_if_exception_is_invalid_user
def _verify_if_exception_is_invalid_user(self, exception):
if 'ORA-01017' in exception.__str__():
CLI.msg('\nPlease inform dba user/password to connect to database "%s"\nUser:' % (self.__host), "END")
dba_user = self.std_in.readline().strip()
passwd = self.get_pass()
conn = self.__driver.connect(dsn=self.__host, user=dba_user, password=passwd)
cursor = conn.cursor()
try:
cursor.execute("create user %s identified by %s" % (self.__user, self.__passwd))
cursor.execute("grant connect, resource to %s" % (self.__user))
cursor.execute("grant create public synonym to %s" % (self.__user))
cursor.execute("grant drop public synonym to %s" % (self.__user))
except Exception, e:
raise Exception("check error: %s" % e)
finally:
示例10: setUp
def setUp(self):
self.mock_sys_exit = self.create_patch("sys.exit")
self.origcwd = os.getcwd()
self.tempdir = create_temp_dir()
os.chdir(self.tempdir)
self.cli = CLI()
示例11: main
def main():
interface = CLI()
commands = (
("I", new_image),
("C", clear),
("L", colour_pixel),
("V", draw_vertical_segment),
("H", draw_horizontal_segment),
("F", fill_region),
("S", show),
("X", terminate),
)
for token, fn in commands:
interface.register_command(token, fn)
interface.main_loop()
示例12: manual_test
def manual_test():
""" Manual test for the CLI if needed. """
to_cli_q = queue.Queue()
from_cli_q = queue.Queue()
cli = CLI(to_cli_q, from_cli_q)
cli.start()
log.info('CLI running state: %r', cli.running)
time.sleep(10)
log.info('CLI running state: %r', cli.running)
cli.stop()
try:
while True:
log.info('Got CLI input: %r', from_cli_q.get(timeout=0.1))
except queue.Empty:
pass
示例13: run
def run():
cli = CLI()
try:
(options, args) = cli.parse()
if options.torneira_version:
msg = "torneira v%s" % torneira.__version__
cli.info_and_exit(msg)
if options.show_colors:
CLI.show_colors()
Main().excecute()
except KeyboardInterrupt:
cli.info_and_exit("\nExecution interrupted by user...")
except Exception, e:
cli.error_and_exit(str(e))
示例14: __init__
def __init__(self, config=None, mysql=None, db_migrate=None):
self.cli = CLI()
self.config = config or {}
self.mysql = mysql
if self.mysql is None and not self.config.get("new_migration"):
self.mysql = MySQL(config)
self.db_migrate = db_migrate or SimpleDBMigrate(config)
示例15: _verify_if_exception_is_invalid_user
def _verify_if_exception_is_invalid_user(self, exception):
import pdb;pdb.set_trace()
#TODO validar como isso funciona no mongodb
if 'ORA-01017' in exception.__str__():
try:
cli = CLI()
cli.msg('\nPlease inform dba user/password to connect to database "%s"\nUser:' % (self.__host), "END")
dba_user = self.std_in.readline().strip()
passwd = self.get_pass()
conn = self.__driver.connect(dsn=self.__host, user=dba_user, password=passwd)
cursor = conn.cursor()
cursor.execute("create user %s identified by %s" % (self.__user, self.__passwd))
cursor.execute("grant connect, resource to %s" % (self.__user))
cursor.execute("grant create public synonym to %s" % (self.__user))
cursor.execute("grant drop public synonym to %s" % (self.__user))
cursor.close()
conn.close()
except Exception, e:
raise Exception("check error: %s" % e)