Python actual combat: virus trapped me in the room, desktop takes me to travel

Tianyuan prodigal son 2020-11-13 09:53:03
python actual combat virus trapped


In modern history , Every year of gengzi is unusual :1840 Opium War of ,1900 The Allied forces of the eight powers invaded China ,1960 The great famine of .2020 This Spring Festival of , A sudden novel coronavirus epidemic sweeping east Asia , It's going to sweep the world . This is a disaster , It made a lot of people give up plans for parties and trips , We have to live in a small room . however , Virus is rampant again , It can't stop programmers from yearning for a better life . today , Let me teach you how to use Python Make a wallpaper switch tool , Show photos of previous trips , Let the table take us around the world !

1. use Python Set up Windows wallpaper

Set up Windnows wallpaper , Need modification Windows The registry , use Python operation Windows The registry , In general use Pywin32 modular . This module packs almost all Windows API, Easy access to Python Call directly .Pywin32 Allow you to look like VC In the same way Python Development win32 application , The code style can be similar to win32 sdk, It can be similar MFC, It's up to you to choose . install Pywin32 modular , You can use the following command to install directly , You can also get it from Python Module warehouse download whl File is installed locally .

python -m pip install pywin32

use Python Set up Windows wallpaper , It is divided into 5 Step , The core code is just 5 That's ok :

import win32api
import win32gui
import win32con
def set_wallpaper(photo_path):
""" Set up wallpaper """
# 1. Open registry key 
key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE)
# 2. Set wallpaper style :0= In the middle 1= tile 2= The tensile 
win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "2")
# 3. Set whether wallpaper is scaled :0= The zoom 1= Original picture 
win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0")
# 4. Set up wallpaper 
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, photo_path, 3)
# 5. Close registry key 
win32api.RegCloseKey(key)

I found a picture of Cherry Blossom blooming in Wulongtan of Jinan last spring , function :

photo_path = r'D:\CSDN\Column\desktop\album\20200129150646.jpg'
set_wallpaper(photo_path)

My desktop is like this in a flash :
 Insert picture description here

Students familiar with the registration form can skip the rest of this section , Go straight to the next section . Students interested in registry structure , You can continue to read this section . Click on Win + R, Input regedit You can open the registry editor of the system , As shown in the figure below :
 Insert picture description here

The registry is divided into left and right parts , On the left is the key directory , On the right is a list of values . Keys and values in the registry , Different from what our programmers usually call keys and values . The key here is similar to the directory , Value similar to file , Each value contains three items : name 、 type 、 data .

Windows The key of the registry of a tree structure , It has six nodes :

  • HKEY_LOCAL_MACHINE: Core primary key of registry , Records the configuration of all hardware and software on the computer
  • HKEY_CLASSES_ROOT: This is not the real node , It is HKEY_LOCAL_MACHINE\Software\Classes Link to , Operation and operation on this node HKEY_LOCAL_MACHINE\Software\Classes It's the same
  • HKEY_USERS: Core primary key of registry , Recorded Windows Settings information for all users in
  • HKEY_CURRENT_USER: yes HKEY_USERS Link to the current user key in , All configuration information of the current login user is saved
  • HKEY_CURRENT_CONFIG: yes HKEY_LOCAL_MACHINE\Config Link to
  • HKEY_DYN_DATA: The dynamic data of the system is recorded

Wallpaper information is different for each user , So we need to operate HKEY_CURRENT_USER The content in , The concrete is HKEY_CURRENT_USER\Control Panel\Desktop, There are three values to modify :

  • WallPaper: Path to wallpaper file
  • WallpaperStyle: There are three options :0= In the middle 1= tile 2= The tensile
  • TileWallpaper: There are two options :0= The zoom 1= Original picture

Use pywin32 Module operation registry , Three steps are required :

  1. Open registry key
    call win32api.RegOpenKeyEx Open registry key , It has four parameters , Respectively :
    • The root node
    • Child node
    • It has to be for 0
    • Actions on open children , Include win32con.KEY_ALL_ACCESS、win32con.KEY_READ、win32con.KEY_WRITE、win32con.KEY_SET_VALUE etc.
  2. Modify registry values
    To modify the value of the registry , When the key is turned on , The fourth parameter needs to be set to win32con.KEY_SET_VALUE, Then you can call win32api.RegSetValueEx Modified value , It has five parameters :
    • Open registry key
    • Name of value
    • It has to be for 0
    • Data type of value , Include win32con.REG_BINARY、win32con.REG_SZ、win32con.REG_DWORD etc.
    • value
  3. Close registry key
    After operating the registry , You can call win32api.RegCloseKey Close registry key

2. Random switching Windows wallpaper

Next , We put the travel photos into a catalogue , Recursively traverse all photos , Then randomly select a wallpaper :

# -*- coding: utf-8 -*-
import os, random
import win32api, win32gui, win32con
def set_wallpaper(photo_path):
""" Set up wallpaper """
# 1. Open registry key 
key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE)
# 2. Set wallpaper style :0= In the middle 1= tile 2= The tensile 
win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "2")
# 3. Set whether wallpaper is scaled :0= The zoom 1= Original picture 
win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0")
# 4. Set up wallpaper 
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, photo_path, 3)
# 5. Close registry key 
win32api.RegCloseKey(key)
def set_wallpaper_random(photo_dir):
""" Random wallpaper """
wall_papers = list()
for root, dirs, files in os.walk(photo_dir):
for name in files:
if os.path.splitext(name)[1].lower() == ".jpg":
wall_papers.append(os.path.join(root, name))
set_wallpaper(random.choice(wall_papers))
if __name__ == '__main__':
#photo_path = r'D:\CSDN\Column\desktop\album\20200129150646.jpg'
#set_wallpaper(photo_path)
set_wallpaper_random(r'D:\CSDN\Column\desktop\album')

This code runs once , You can randomly switch a wallpaper . I ran 4 Time ,4 Desktop effects are as follows :
 Insert picture description here

3. Timing switch Windows wallpaper

Every time I want to change the wallpaper , You need to run the above code manually , It's a little bit of a hassle . Good. , Let's make an automatic timing switch . Realize timing switching function , Need a scheduling service framework . I just introduced it in the data capture service the other day APScheduler library , Today we continue to use it to achieve the scheduled execution of tasks .APScheduler The installation command is as follows :

python -m pip install apscheduler

After installation, you can test the effect with the following code :

from apscheduler.schedulers.blocking import BlockingScheduler
# Task execution function 
def do_job():
print("do_job")
# Create scheduler 
scheduler = BlockingScheduler()
# add to job
scheduler.add_job(do_job, # Execution function after time 
trigger="cron", # Set trigger to cron 
second="*/1", # Set to execute every second 
misfire_grace_time=60 # If there are more tasks ,60 No urgent execution within seconds job when , Give up execution 
)
# Start scheduling 
scheduler.start()

If it can be printed out every second do_job, explain apscheduler It can be executed normally .apscheduler There are many kinds of triggers , In this code , Used cron trigger , This is a apscheduler The most complex trigger in , It can be used cron grammar , Specify a very complex way to trigger .

cron Syntax contains seconds 、 minute 、 Hours 、 Japan 、 month 、 week 、 Seven domains in , Some wildcards can be used in each domain , Used to match when tasks can be performed , When 7 When all domains are matched successfully , The task will be performed . The following wildcards are supported for each domain :

  • second : You can use ", - * /" Four characters and valid range 0-59 The integer of
  • minute : You can use ", - * /" Four characters and valid range 0-59 The integer of
  • Hours : Can appear ", - * /" Four characters and valid range 0-23 The integer of
  • Japan : You can use ", - * / ? L W C" Eight characters and valid range 0-31 The integer of
  • month : You can use ", - * /" Four characters 、 The valid range is 1-12 An integer of or JAN-DEC
  • week : You can use ", - * / ? L C #" Four characters 、 The valid range is 1-7 An integer of or SUN-SAT Two ranges .1 Sunday ,2 For Monday , By analogy
  • year : You can use ", - * /" Four characters 、 The valid range is 1970-2099 year

among , The meaning of each character is as follows :

  • , Indicates that enumeration values are listed .

     stay “ minute ” Domain use 5,20, It means in 5 and 20 Trigger twice
    
  • - Scope of representation .

     stay “ minute ” Domain use 5-20, From 5 be assigned to 20 Trigger every minute
    
  • * Represents any value that matches the field .

     stay “ minute ” Domain use *, It means that the event will be triggered every minute
    
  • / Indicates that the start time starts to trigger , Then trigger every fixed time .

     stay “ minute ” Domain use 5/20, Means that the 5 Minutes to trigger , Later interval 20 Minutes to trigger , namely 5、25、45 Wait for each trigger
    
  • ? Also matches any value of the field , But it can only be used in “ Japan ” and “ week ” Two domain . because “ Japan ” and “ week ” Will affect each other , When “ Japan ” and “ week ” One of them uses * Other rules , The other should use ? They can't be used *.

     Want to 20 Daily trigger dispatch , No matter 20 What day is the day of the week , You can only write it as follows :
    Japan :20, month :*, week :?
    
  • L Said the last , Can only appear in “ Japan ” and “ week ” Domain .

     stay “ week ” Domain use 5L, Means trigger on the last Thursday
    
  • W Means effective working day ( Monday to Friday ), Can only appear in “ Japan ” Domain , The system will trigger the event... On the most effective working day from the specified date .

     stay day Use 5W, If 5 It's Saturday , On the most recent working day : Friday , namely 4 Day trigger . If 5 Sunday is Sunday , It's in 6 Japan ( Monday ) Trigger ;
    If 5 A day from Monday to Friday , It's in 5 Day trigger . Another point ,W Our latest search will not cross the month .
    
  • LW These two characters can be used together , On the last working day of a month , The last Friday

  • # Used to determine the week ordinal of each month , Can only appear in “ week ” Domain .

     stay 4#2, The second Wednesday of a month
    

Change the above code a little, and you can switch wallpaper regularly :

# -*- coding: utf-8 -*-
import os, random
import win32api, win32gui, win32con
from apscheduler.schedulers.blocking import BlockingScheduler
def set_wallpaper(photo_path):
""" Set up wallpaper """
# 1. Open registry key 
key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE)
# 2. Set wallpaper style :0= In the middle 1= tile 2= The tensile 
win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "2")
# 3. Set whether wallpaper is scaled :0= The zoom 1= Original picture 
win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0")
# 4. Set up wallpaper 
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, photo_path, 3)
# 5. Close registry key 
win32api.RegCloseKey(key)
def set_wallpaper_random(photo_dir):
""" Random wallpaper """
wall_papers = list()
for root, dirs, files in os.walk(photo_dir):
for name in files:
if os.path.splitext(name)[1].lower() == ".jpg":
wall_papers.append(os.path.join(root, name))
set_wallpaper(random.choice(wall_papers))
def set_wallpaper_regular(photo_dir):
""" Timing wallpaper """
scheduler = BlockingScheduler()
scheduler.add_job(set_wallpaper_random,
args = (photo_dir, ),
trigger = "cron",
second = "*/10" # Every time 10 Once per minute 
)
scheduler.start()
if __name__ == '__main__':
#photo_path = r'D:\CSDN\Column\desktop\album\20200129150646.jpg'
#set_wallpaper(photo_path)
#set_wallpaper_random(r'D:\CSDN\Column\desktop\album')
set_wallpaper_regular(r'D:\CSDN\Column\desktop\album')

Run this code , every other 10 Minute auto wallpaper . Interested students , It can also be packaged as a service program , And even a task tray program , Will be more practical .

版权声明
本文为[Tianyuan prodigal son]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database