简体   繁体   English

如何从Python脚本执行Cassandra CLI命令?

[英]How do I execute Cassandra CLI commands from a Python script?

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. 我有一个python脚本,可以用来在服务器上进行远程调用,连接到Cassandra CLI并执行命令来创建键空间。 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()

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. 例如,上面的代码抛出“ / bin / sh:1:CREATE:not found”,我认为这意味着它没有在CLI命令行上执行CREATE语句。

Any/all help would be GREATLY appreciated! 任何/所有帮助将不胜感激! Thank you! 谢谢!

try this out. 试试这个。 I don't have cassandra-cli installed on my machine, so I couldn't test it myself. 我的机器上没有安装cassandra-cli,所以我自己无法测试。

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 you mentioned in the comment below pycassa a Python client for Cassandra cannot be used since it doesn't seem to support create statements. 正如您在pycassa下方的评论中提到的那样,不能使用Cassandra的Python客户端,因为它似乎不支持create语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM