记录一些python脚本。能看懂则借鉴吧,不能看懂别勉强!!!
1、启动java应用服务:
#!/usr/bin/env python
# coding: utf-8
import os
import time
import socket
import subprocess
class JavaServer:
def __init__(self, command, port):
self.command = command
self.port = port
self.server_start_all()
def server_start_all(self):
fnull = open(os.devnull, 'w')
result = subprocess.call(self.command, shell=True, stdout=fnull, stderr=fnull)
current_time = time.strftime('%Y%m%d-%H%M%S', time.localtime())
time.sleep(1) # 延迟1秒
if result:
print('时间:{}---执行命令:{} 失败'.format(current_time, self.command))
return False
else:
print('时间:{}---执行命令:{} 成功'.format(current_time, self.command))
self.check_aliveness()
fnull.close()
def check_aliveness(self):
hostname = socket.gethostname() # 获取主机名
ip = socket.gethostbyname(hostname) # 获取主机ip地址
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk.settimeout(1)
try:
sk.connect((ip, self.port))
print('server:{} 端口:{} is OK '.format(ip, self.port))
self.server_port = 'ok'
except Exception:
print('sever:{} 端口:{} is NOT OK '.format(ip, self.port))
return False
finally:
sk.close()
if __name__ == '__main__':
command_list = [['/usr/local/zookeeper-3.4.6/bin/zkServer.sh start', 3888],
['sh /usr/java/account/bin/startup.sh &', 20678],
['sh /usr/java/order/bin/startup.sh &', 20999],
['sh /usr/java/user/bin/startup.sh &', 20001],
['sh /usr/java/system/bin/startup.sh &', 20888]
]
while True:
for i in command_list:
st = JavaServer(i[0], i[1])
print(st.__dict__)
if st.__dict__['server_port'] == 'ok':
pass
else:
print('服务:{}开启失败'.format(i[0]))
break
break
2、利用pymysql结合协程快速创建3000万条测试数据
import pymysql
import gevent
import time
class MyPyMysql:
def __init__(self, host, port, username, password, db, charset='utf8'):
self.host = host
self.port = port
self.username = username
self.password = password
self.db = db
self.charset = charset
self.pymysql_connect()
def pymysql_connect(self):
self.conn = pymysql.connect(host=self.host,
port=self.port,
user=self.username,
password=self.password,
db=self.db,
charset=self.charset
)
self.asynchronous()
def run(self, nmin,nmax):
self.cur = self.conn.cursor()
sql = "insert into userinfo(id,name,gender,email) values (%s,%s,%s,%s)"
data_list = []
for i in range(nmin, nmax):
result = (i, 'zhangsan' + str(i), 'male', 'zhangsan' + str(i) + '@qq.com')
data_list.append(result)
content = self.cur.executemany(sql, data_list)
if content:
print('成功插入第{}条数据'.format(nmax))
else:
print('3000万数据插入完毕')
self.conn.commit()
def asynchronous(self):
g_l = [gevent.spawn(self.run, i, i+10000) for i in range(1, 30000001, 10000)]
gevent.joinall(g_l)
self.cur.close()
self.conn.close()
if __name__ == '__main__':
start_time = time.time()
st = MyPyMysql('192.168.11.200', 3306, 'root', 'root', 'db2')
print('程序耗时{:.2f}'.format(time.time() - start_time))
后期更新。。。