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

℡╲_俬逩灬. 提交于 2020-01-11 11:07:31

问题


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()

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!


回答1:


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 you mentioned in the comment below pycassa a Python client for Cassandra cannot be used since it doesn't seem to support create statements.



来源:https://stackoverflow.com/questions/13347534/how-do-i-execute-cassandra-cli-commands-from-a-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!