如何从Python脚本执行Cassandra CLI命令? [英] How do I execute Cassandra CLI commands from a Python script?
问题描述
我有一个python脚本,可以用来在服务器上进行远程调用,连接到Cassandra CLI并执行命令来创建键空间。我为此所做的尝试之一是:
I have a python script that I want to use to make remote calls on a server, connect to Cassandra CLI, and execute commands to create keyspaces. One of the attempts that I made was something to this effect:
connect="cassandra-cli -host localhost -port 1960;"
create_keyspace="CREATE KEYSPACE someguy;"
exit="exit;"
final = Popen("{}; {}; {}".format(connect, create_keyspace, exit), shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
stdout, nothing = final.communicate()
通过各种解决方案,我没有找到我需要的东西。例如,上面的代码抛出 / bin / sh:1:CREATE:not found,我认为表示它没有在CLI命令行上执行CREATE语句。
Looking through various solutions, I'm not finding what I need. For example, the above code is throwing a "/bin/sh: 1: CREATE: not found", which I think means that it's not executing the CREATE statement on the CLI command line.
任何/所有帮助将不胜感激!谢谢!
Any/all help would be GREATLY appreciated! Thank you!
推荐答案
尝试一下。我的机器上没有安装cassandra-cli,所以我自己也无法测试。
try this out. I don't have cassandra-cli installed on my machine, so I couldn't test it myself.
from subprocess import check_output
from tempfile import NamedTemporaryFile
CASSANDRA_CMD = 'cassandra-cli -host localhost -port 1960 -f '
def cassandra(commands):
with NamedTemporaryFile() as f:
f.write(';\n'.join(commands))
f.flush()
return check_output(CASSANDRA_CMD + f.name, shell=True)
cassandra(['CREATE KEYSPACE someguy', 'exit'])
As您在下面的注释中提到的 pycassa Cassandra的Python客户端不能使用,因为它似乎无法支持创建语句。
As you mentioned in the comment below pycassa a Python client for Cassandra cannot be used since it doesn't seem to support create statements.
这篇关于如何从Python脚本执行Cassandra CLI命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!