一.使用模块
Python本身就内置了很多非常有用的模块,只要安装完毕,这些模块就可以立刻使用。
1.python中内置的模块
# import time
# time.time()
# time.ctime()
# time.sleep(2)
#
# import math
import os
print(os.listdir('/var/log'))
import random
import string
random.random()
random.randint(1,4)
random.choice('hello')
random.sample(string.ascii_letters,4)
random.shuffle(list(range(1,10)))
2.导入第三方模块生成一个二维码,扫描后跳转到baidu.com
第三方模块介绍:
在Python中,安装第三方模块,是通过包管理工具pip完成的。
如果你正在使用Mac或Linux,安装pip本身这个步骤就可以跳过了。
代码:
import qrcode
#img = qrcode.make('hello world')
img = qrcode.make('http://www.baidu.com')
img.save('hello.png')
3.导入第三方模块统计你的好友的男女比例
代码:
import itchat
import time
import random
#while True:
##如果加上参数hotReload==True ,就会保留登录状态,在短时间内重新登录不用再次扫描二维码。
# 该参数在当前目录生成一个静态文件itchat.pkl用于存储登录状态
# itchat.auto_login(hotReload=True)
# #给手机助手发送消息
# #itchat.send('hello',toUserName='filehelper')
# itchat.send_file('/etc/passwd',toUserName='filehelper')
# time.sleep(random.randint(1,3))
#2.统计你的好友的男女比例
itchat.auto_login(hotReload=True)
friends =itchat.get_friends()
# fridnes是一个列表数据类型,其中起一个是自己的信息,除了第一个之外的是你的好友的信息
#print(friends)
info ={}
for friend in friends[1:]:
if friend['Sex'] == 1:
info['male'] = info.get('male',0) + 1
elif friend['Sex'] == 2:
info['female'] = info.get('female',0) + 1
else:
info['other'] = info.get('other',0) + 1
print(info)
4.创建一个图灵机器人,能跟你的微信好友自动对话
代码:
def get_tuling_response(_info):
print(_info)
# 图灵机器人的api网址
api_url = 'http://www.tuling123.com/openapi/api'
data = {
'key':'55f5db4f976d4de38302c333e8848a1d',
'info':_info,
'userid':'lily'
}
# 发送数据到指定的网址,获取网址返回的数据
res = requests.post(api_url,data).json()
#print(res,type(res))
print(res['text'])
return res['text']
# get_tuling_response('给我讲个笑话')
# get_tuling_response('给我讲个故事')
# 时刻监控好友发送的文本信息,别给予一个回复
# 注册消息响应事件。消息的类型为itchat.content.TEXT,即文本消息
@itchat.msg_register(itchat.content.TEXT,isFriendChat=True)
def text_reply(msg):
# 获取好友发送的消息内容
# 返回同样的文本消息
content = msg['Content']
# 将好友的消息发送给机器人去处理,处理的结果就是返回给好友的消息
returnContent = get_tuling_response(content)
#time.sleep(random.randint(1,10))
return returnContent
itchat.auto_login(hotReload=True)
# 绑定消息响应事件后,让itchat运行起来
itchat.run()
5.用你的微信文件助手远程执行你的linux中的shell命令
import os
import itchat
# # 在python里面执行shell命令
# # 1.第一种方式:可以判断命令是否执行成功;返回值为0
# # 执行成功,返回值不为0,则不成功
# res = os.system('hostnames')
# print(res)
# 2.第二种方式:用来保存命令的执行结果
res = os.popen('hostname').read()
print(res)
@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
"""
需求:当文件助手发送消息,执行发送的内容
1.如果执行成功:【显示执行成功】:执行结果
2.反之,显示执行失败
"""
print(msg)
if msg['ToUserName'] == 'filehelper':
# 获取要执行命令的内容
command = msg['Content']
print(command)
# 让电脑执行命令代码
# 如果执行成功,返回值是0
if os.system(command) == 0:
res = os.popen(command).read()
result = '[返回值] - 命令执行成功,执行结果:\n' + res
itchat.send(result, 'filehelper')
# 命令执行失败
else:
result = '返回值] - 命令%s执行失败,请重试' % command
itchat.send(result,'filehelper')
itchat.auto_login(hotReload=True)
itchat.run()