• python 模块


    1. 小程序:根据用户输入选择可以完成以下功能

      ** 创意文件,如果路径不存在,创建文件夹后再创建文件
      能够查看当前路径
      在当前目录及其所有子目录下查找文件名包含指定字符串的文件 **

      #!/bin/python3
      # -*- coding:utf-8 -*-
      import os,sys
      
      def create(file_path):
          if not file_path:
              return
          if not os.path.exists(file_path):
              dir_name = os.path.dirname(file_path)
              file_name = os.path.basename(file_path)
              if dir_name == '':
                  file1 = open(file_path, mode='w')
                  file1.close()
                  print("%s created" %file_path)
              else:
                  if not os.path.exists(dir_name):
                      os.makedirs(dir_name)
                  file1 = open(file_path, mode='w')
                  file1.close()
                  print("%s created" %file_path)
          else:
              print("file already exists")
      def currentpath():
          print(os.getcwd())
      def search(str1):
          path_list = os.walk(os.getcwd())
          temp_list = []
          # file_path = ('%s/%s'%(x[0],y) for x in path_list for y in x[-1])
          for x in path_list:
              for y in x[-1]:
                  temp_list.append(os.path.join(x[0],y))
          for x in temp_list:
              file_name = os.path.basename(x)
              if str1 in file_name:
                  print(x)
      def main():
          file_action = {
              '1':create,
              '2':currentpath,
              '3':search
          }
          while True:
              print("------------------
      1.create
      2.currentpath
      3.search
      ------------------
      # ",end='')
              choice = input(">")
              if choice not in file_action:
                  continue
              if choice == '1':
                  file_path = input("create file:")
                  file_action[choice](file_path)
              if choice == '2':
                  file_action[choice]()
              if choice == '3':
                  search_str = input("keyword:")
                  file_action[choice](search_str)
      if __name__ == '__main__':
          main()
      
    2. 将三次登陆锁定的作业改为:
      ** python login.py -u alex -p 123456 输入的形式(-u,-p是固定的,分别代表用户名和密码) **

      #!/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)+"
      "
                      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)+"
      "
                      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:
      -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函数。 **
      在dir1目录内添加__init__.py,main.py内为sys.path添加上级目录

      import sys
      print(sys.path)
      sys.path.append("..")
      print(sys.path)
      import dir1.hello
      print(dir1.hello.add(1, 5))
      
    4. 显示当前时间三天后是星期几?

      import time
      def week_display(after_days):
          second_time = time.time()
          second_time += 86400 * after_days
          local_time = time.localtime(second_time)
          print(time.strftime("%A",local_time ))
      week_display(2)
      
  • 相关阅读:
    Memcached 笔记与总结(9)Memcached 与 Session
    python禁止函数修改列表的实现方法
    python禁止函数修改列表的实现方法
    大数据是工业的核心资源 企业入局需合理把握
    大数据是工业的核心资源 企业入局需合理把握
    Python执行时间的计算方法小结
    Python执行时间的计算方法小结
    大数据无处不在 企业实践指南有哪些?
    大数据无处不在 企业实践指南有哪些?
    python条件变量之生产者与消费者操作实例分析
  • 原文地址:https://www.cnblogs.com/anyanyaaaa/p/6770268.html
Copyright © 2020-2023  润新知