pythn调用shll命令:创建hbase表
融合python的类库和shell的全部功能于一体: 在python脚本中调用shell命令
- 1,使用python解析参数
- 2,调用shell命令,并获取对应的输出结果
py_shell_arr.sh: 脚本内容如下
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os,sys
#定义数组
table_prefix="xyz"
#arr=(12,13,)
arr=sys.argv[1:] #接收全部参数
if len(arr)<1 :
print("至少需要一个参数: tablename !"); sys.exit() #退出程序
for x in arr:
#print(x)
#调用shell脚本
os.system("echo elem ="+str(x)) #打印输入的参数
os.system("echo '"+str(x)+"' >> a.txt") #输入写入文件
#创建hbase表
#os.system("echo exists \"\'xyz"+ str(x) +"\'\" |hbase shell |grep 'does exist' ; echo $?" )
result=os.popen("echo exists \"\'" + table_prefix + str(x) +"\'\" |hbase shell |grep 'does exist' " )
# 判断表是否存在
if (len(result.read() )>0) :
print("表已存在....")
else:
print("表不存在,creating....")
os.system("echo create \"\'"+ table_prefix + str(x)+ "\'\",\"\'f\'\" |hbase shell") #调用hbase 命令: 传递参数,创建hbase表
status=os.popen("echo $?").read().strip()
print("stat="+status)
if status == "0":
print("创建成功!")
else:
print("创建失败!")
测试脚本
[email protected]:~/sh/py$ ./py_shell_arr.sh
至少需要一个参数: tablename !
[email protected]:~/sh/py$ ./py_shell_arr.sh a b c
elem =a
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
表不存在,creating....
Type "exit<RETURN>" to leave the HBase Shell
Version 1.2.6, rUnknown, Mon May 29 02:25:32 CDT 2017
create 'xyza','f'
0 row(s) in 2.5530 seconds
Hbase::Table - xyza
stat=0
创建成功!
elem =b
........................