python(31)- 模块练习
1. 小程序:根据用户输入选择可以完成以下功能:
创意文件,如果路径不存在,创建文件夹后再创建文件
能够查看当前路径
在当前目录及其所有子目录下查找文件名包含指定字符串的文件
import os
choice={
"1":"创建文件",
"2":"查看当前路径",
"3":"查找文件名",
"4":"退出程序"
} def mkdir():
file_path = input("please input your file_path:").strip()
try:
os.chdir(file_path)
print("%s存在,不需要重新创建" % file_path)
except:
print("%s不存在,开始创建文件" % file_path)
os.makedirs(file_path)
print("%s创建完成" % file_path) def check():
file_name = input("please input your file_name:").strip()
try:
print("%s绝对路径为:%s"%(file_name,os.path.abspath(file_name)))
except:
print("%s不存在,开始创建文件" % file_name) def search():
file_dir = input("please input your file_dir:").strip()
print("当前目录为:%s,子目录和所有文件为:%s" % (os.getcwd(), os.listdir(os.getcwd()))) while True:
for key in choice:
print(key,choice[key])
num=int(input("please input your choice:").strip()) if num==1:
mkdir() elif num==2:
check() elif num == 3:
search() elif num==4:
break
2. 将三次登陆锁定的作业改为:python login.py -u alex -p 123456 输入的形式(-u,-p是固定的,分别代表用户名和密码)
#将三次登陆锁定的作业改为:
# python login.py -u alex -p 123456 输入的形式
# (-u,-p是固定的,分别代表用户名和密码)
import sys
if(sys.argv[sys.argv.index("-u")+1] == "egon" and sys.argv[sys.argv.index("-p")+1] == "somebody" ):
print("Congratulations")
else:
print("Error")
#!/bin/python3
# -*- coding:utf-8 -*-
''' python login auth example '''
#imports
import getpass,os,sys
#functions
def lock_user(username):
''' username -> modify userlist file '''
temp_str = ""
with open("userlist.swp",'w') as file_write , open("userlist",'r') as file_read:
for line in file_read:
temp_list = eval(line)
if temp_list[0] == username:
temp_list[2] += 1
temp_str += str(temp_list)+"\n"
continue
temp_str += line
file_write.write(temp_str)
os.rename("userlist.swp", "userlist")
def unlock_user(username):
''' username -> modify userlist file '''
temp_str = ""
with open("userlist.swp",'w') as file_write , open("userlist",'r') as file_read:
for line in file_read:
temp_list = eval(line)
if temp_list[0] == username:
temp_list[2] = 0
temp_str += str(temp_list)+"\n"
continue
temp_str += line
file_write.write(temp_str)
os.rename("userlist.swp", "userlist")
def user_input():
''' input username&&password -> return username&&password '''
if not "-u" in sys.argv and not "-p" in sys.argv:
print("help:\n-u [username] -p [password]")
exit()
username = sys.argv[sys.argv.index("-u")+1]
password = sys.argv[sys.argv.index("-p")+1]
# username = input("username:")
# password = getpass.getpass("password:")
return username,password
def check_user(username,password = '',type = 'check'):
'''
username,password,check -> return t||f #username password lock check
username,password,lock -> return t||f #username locked or not
'''
flag = False
with open("userlist",'r') as file_read:
for line in file_read:
temp_list = eval(line)
if type == 'check':
if username == temp_list[0] and password == temp_list[1] \
and temp_list[2] < 2:
return True #user not locked and correct user and pass
if type == 'lock':
if username == temp_list[0] and temp_list[2] >= 2:
return True #user has been locked else:
return False
#login decorator
def auth(func):
def wrapper(*args,**kwargs):
username,password = user_input() #get input
# if not username and not password:
# print("incorrect username or password!")
# exit()
if check_user(username, password,type='check'): #juge username and password correct or not
print("login success!")
unlock_user(username)
func(username) #shell function
else:
if check_user(username, password, type='lock'): #juge user locked or not
print("This account has been locked!")
else:
lock_user(username) #lock count += 1
print("incorrect username or password!")
return wrapper
#shell function
@auth
def login_index(username = ""):
''' shell program '''
while True:
command = input("%s>" %username) #ask input command
if command == 'ls':
print(
'''
bin dev home lib64 media opt root sbin sys usr
boot etc lib lost+found mnt proc run srv tmp var
''')
if command == 'exit': #exit shell
print("byebye!")
exit() def main():
''' main program '''
login_index() #program entry
if __name__ == '__main__':
main()
3. 层级结构:
dir1
---hello.py
dir2
---main.py
其中,hello.py:
def add(x,y):
return x+y
main.py如何能调用到hello.py中的add函数?
参考博客结尾的内容,单独导入包。http://www.cnblogs.com/xuyaping/p/6797032.html
注:此题中导入的模块只是一个简单的模块,和博客中导入模块不同的是没有__init__文件,更简单些。
#main.py
import sys,os
sys.path.append("E:\python学习\day33常用模块\作业\dir1")
print(sys.path)
--->['E:\\python学习\\day33常用模块\\作业\\dir2', 'E:\\python学习', 'C:\\Users\\Administrator.PC-201509301704\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\Administrator.PC-201509301704\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\Administrator.PC-201509301704\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\Administrator.PC-201509301704\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\Administrator.PC-201509301704\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages', 'E:\\python学习\\day33常用模块\\作业\\dir1'] import hello
print(hello.add(1,2))
--->3
4. 显示当前时间三天后是星期几?
import time
c=time.localtime()
print(c) #当前时间
--->time.struct_time(tm_year=2017, tm_mon=4, tm_mday=26, tm_hour=23, tm_min=40, tm_sec=54, tm_wday=2, tm_yday=116, tm_isdst=0) t=time.time()-3600*24*3
print(time.localtime(t))
--->time.struct_time(tm_year=2017, tm_mon=4, tm_mday=23, tm_hour=23, tm_min=44, tm_sec=30, tm_wday=6, tm_yday=113, tm_isdst=0) print(time.localtime(t).tm_wday)
--->6
python(31)- 模块练习的更多相关文章
- python基础-模块
一.模块介绍 ...
- Day05 - Python 常用模块
1. 模块简介 模块就是一个保存了 Python 代码的文件.模块能定义函数,类和变量.模块里也能包含可执行的代码. 模块也是 Python 对象,具有随机的名字属性用来绑定或引用. 下例是个简单的模 ...
- python 各模块
01 关于本书 02 代码约定 03 关于例子 04 如何联系我们 1 核心模块 11 介绍 111 内建函数和异常 112 操作系统接口模块 113 类型支持模块 114 正则表达式 115 语言支 ...
- python random模块 - 小驹的专栏 - 博客频道 - CSDN.NET
python random模块 - 小驹的专栏 - 博客频道 - CSDN.NET python random模块 分类: python 2011-11-15 15:31 6037人阅读 评论(2) ...
- Day5 模块及Python常用模块
模块概述 定义:模块,用一砣代码实现了某类功能的代码集合. 为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,提供了代码的重用性.在Python中,一个.py文件就称之为一个模块(Mod ...
- SUSE Linux Enterprise 11 离线安装 DLIB python机器学习模块
python机器学习模块安装 环境:SUSE Linux Enterprise 11 sp4 离线安装 说明:在安装dlib时依赖的基础 环境较多,先升级gcc,以适应c++ 11的使用:需要用到c ...
- Python(五)模块
本章内容: 模块介绍 time & datetime random os sys json & picle hashlib XML requests ConfigParser logg ...
- Thread类的其他方法,同步锁,死锁与递归锁,信号量,事件,条件,定时器,队列,Python标准模块--concurrent.futures
参考博客: https://www.cnblogs.com/xiao987334176/p/9046028.html 线程简述 什么是线程?线程是cpu调度的最小单位进程是资源分配的最小单位 进程和线 ...
- Python之模块和包
一.模块 1.什么是模块? 常见的场景:一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 但其实import加载的模块分为四个通用类别: 1 使用python编 ...
- python常用模块之时间模块
python常用模块之时间模块 python全栈开发时间模块 上次的博客link:http://futuretechx.com/python-collections/ 接着上次的继续学习: 时间模块 ...
随机推荐
- [windows篇][关掉某些服务]
- 在Notepad++里配置python环境
首先在语言里选择Python 然后点击运行,在弹出的对话框里输入: cmd /k cd /d "$(CURRENT_DIRECTORY)" & python " ...
- 【Luogu】P3232游走(高斯消元解概率)
题目链接 参见远航之曲dalao的题解,我再写一遍的话就没啥意思了. #include<cstdio> #include<cstring> #include<algori ...
- [NOIP2017] 逛公园 (最短路,动态规划&记忆化搜索)
题目链接 Solution 我只会60分暴力... 正解是 DP. 状态定义: \(f[i][j]\) 代表 \(1\) 到 \(i\) 比最短路长 \(j\) 的方案数. 那么很显然最后答案也就是 ...
- bzoj3997[TJOI2015]组合数学(求最长反链的dp)
组合数学 给出一个网格图,其中某些格子有财宝,每次从左上角出发,只能向下或右走.问至少走多少次才能将财宝捡完.此对此问题变形,假设每个格子中有好多财宝,而每一次经过一个格子至多只能捡走一块财宝,至少走 ...
- bzoj 4007 树形dp
题目大意 脸哥最近来到了一个神奇的王国,王国里的公民每个公民有两个下属或者没有下属,这种关系刚好组成一个 n 层的完全二叉树.公民 i 的下属是 2 * i 和 2 * i +1.最下层的公民即叶子节 ...
- foj 2144 三位几何+区间覆盖
题目大意:一个人站在三维坐标系下的原点处用炮打蚊子,给出n个蚊子的起始坐标跟单位时间匀速移动的方向向量,距离他R以内的蚊子都可以打到,不过他也需要休息,没蚊子的时候也可以休息下.求他要起来多少次打蚊子 ...
- BZOJ 4077 Messenger
Messenger [问题描述] alice和bob各自在两条折线上行进,一个邮递员要从alice那拿一个包裹,并以直线移动到bob处,alice和bob.邮递员的速度均为1单位/s,问邮递员最少要走 ...
- 标准C程序设计七---70
Linux应用 编程深入 语言编程 标准C程序设计七---经典C11程序设计 以下内容为阅读: <标准C程序设计>(第7版) 作者 ...
- 共享内存之——mmap内存映射
共享内存允许两个或多个进程共享一给定的存储区,因为数据不需要来回复制,所以是最快的一种进程间通信机制.共享内存可以通过mmap()映射普通文件 (特殊情况下还可以采用匿名映射)机制实现,也可以通过sy ...