python以本机格式打印CQL输出
我有一个python程序,它试图使用python cassandra驱动程序连接到apache cassandra并执行一些查询。我得到的结果集不是列表就是字典。但是,我希望输出以本机cql输出格式(列和行)打印回用户 像这样,python以本机格式打印CQL输出,python,python-2.7,Python,Python 2.7,我有一个python程序,它试图使用python cassandra驱动程序连接到apache cassandra并执行一些查询。我得到的结果集不是列表就是字典。但是,我希望输出以本机cql输出格式(列和行)打印回用户 像这样, keyspace | durable_writes | name | strategy_class | strategy_options ----------+----------------+---------+----------------+-------
keyspace | durable_writes | name | strategy_class | strategy_options
----------+----------------+---------+----------------+--------------------- -------
history | True | history | SimpleStrategy | {"replication_factor":"1"}
ks_info | True | ks_info | SimpleStrategy |{"replication_factor":"1"}
(2 rows)
是否有一个模块我可以用来实现这一点?我使用以下代码来测试
from cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider
from cassandra.query import dict_factory
def fireCql(cqlStatement):
auth_provider = PlainTextAuthProvider(
username='myusername', password='myPassWord')
cluster = Cluster(['cassandra.myhostname.com'],auth_provider=auth_provider)
session = cluster.connect('my_keyspace')
session.row_factory = dict_factory
rows = session.execute(cqlStatement)
return rows
Python:2.7我不相信这是Python驱动程序本身的一个特性。如果您认为很多人会想要这个,您可以向python驱动程序组请求它 但是,下面是Cassandra用来生成格式的代码。您可以使用它作为实现逻辑的基础,以解析您的结果并根据需要设置格式 从
def print_formatted_result(self, formatted_names, formatted_values):
# determine column widths
widths = [n.displaywidth for n in formatted_names]
if formatted_values is not None:
for fmtrow in formatted_values:
for num, col in enumerate(fmtrow):
widths[num] = max(widths[num], col.displaywidth)
# print header
header = ' | '.join(hdr.ljust(w, color=self.color) for (hdr, w) in zip(formatted_names, widths))
self.writeresult(' ' + header.rstrip())
self.writeresult('-%s-' % '-+-'.join('-' * w for w in widths))
# stop if there are no rows
if formatted_values is None:
self.writeresult("")
return
# print row data
for row in formatted_values:
line = ' | '.join(col.rjust(w, color=self.color) for (col, w) in zip(row, widths))
self.writeresult(' ' + line)
self.writeresult("")