Skip to content

Python CLI like API

Dmitry Romanov edited this page Nov 17, 2015 · 3 revisions

Automating ccdb command for scripting purposes could be made easy with python. One doesn't have to call subprocess.

One can use CCDB directly from python using ConsoleContext class.

  1. Add $CCDB_HOME/python to your PYTHONPATH. PYTHONPATH is automatically adjusted when environment.bash CCDB script is sourced. But one can add manually like:
export PYTHONPATH="$CCDB_HOME/python":"$PYTHONPATH"
  1. Usage example
import ccdb.path_utils
import ccdb.cmd.themes
from ccdb import get_ccdb_home_path
from ccdb.cmd.console_context import ConsoleContext

#Initialization
#=============================

#connection strings:
ccdb_path = get_ccdb_home_path()
sqlite_connection_str = "sqlite:///" + os.path.join(ccdb_path, "sql", "ccdb.sqlite")
mysql_connection_str = "mysql://[email protected]:3306/ccdb"

#create console context, this is the main class
context = ConsoleContext()

#set all exception to be raised and propagated instead of just going to log
#so you can try-except them
context.silent_exceptions = False  

# disable colored output
context.theme = ccdb.cmd.themes.NoColorTheme()

# set connection string
context.connection_string = sqlite_connection_str  

# your username for logging
context.user_name = "python_tests"

# Register all commands (ls, rm, mktbl etc...)
# One can use context after calling this function
context.register_utilities()

#now you can use context to run ccdb command
try:
context.process_command_line("mkdir /test/testable2 x y z #Some comment")
#...

Please look at
$CCDB_HOME/python/tests/test_console_context.py
There are a lot of examples of how to use console_context class