我有一个 python 脚本,我想用它在服务器上进行远程调用、连接到 Cassandra CLI 并执行命令以创建键空间。我所做的其中一项尝试就是达到这种效果:
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 语句。
任何/所有帮助将不胜感激!谢谢!
请您参考如下方法:
试试这个。我的机器上没有安装 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 a Python client for Cassandra不能使用,因为它似乎不支持创建语句。
