如何从python脚本执行cassandra cli命令?

q43xntqr  于 2021-06-10  发布在  Cassandra
关注(0)|答案(1)|浏览(349)

我有一个python脚本,我想用它在服务器上进行远程调用,连接到cassandracli,并执行命令来创建键空间。我的一次尝试就是这样的:

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:notfound”,我认为这意味着它没有在cli命令行上执行create语句。
任何/所有帮助都将不胜感激!谢谢您!

6ovsh4lw

6ovsh4lw1#

试试这个。我的机器上没有安装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'])

正如您在pycassa下面的评论中提到的,cassandra的python客户机不能使用,因为它似乎不支持create语句。

相关问题