python实现windows休眠

#关键代码
import subprocess
subprocess.Popen(“rundll32 powrprof.dll,SetSuspendState Hibernate”)

AI吧Python
#关键代码
import subprocess
subprocess.Popen("rundll32 powrprof.dll,SetSuspendState Hibernate")

利用python实现Windows8定时自动关机和休眠

我觉得Window8有一个重大的优点就是支持休眠的功能,休眠以后再次开机可以保持原来已经打开的窗口。但是我发现我的电脑休眠以后会自己开机,也不知道怎么回事,于是我想可以利用python来实现在固定时间内自动关机或者休眠的功能。主要的思路如下:

获取当前时间->与设定的时间作比较->超出了设定时间->关机或休眠

代码如下:

#coding=utf-8
import time, os ,threading

class TimeCmp:
    def __init__(self, TimeStart, TimeEnd):
        self.TimeStart=TimeStart
        self.TimeEnd=TimeEnd
    def GetNowTime(self):
        pass
        #now = time.strftime("%Y-%m-%d %H:%M:%S")
    def Cmp(self):
        LocalTime=time.localtime(time.time())
        self.__TimeNow_1=LocalTime.tm_hour*3600+LocalTime.tm_min*60+LocalTime.tm_sec
        self.__TimeStart_1=3600*self.TimeStart[0]+60*self.TimeStart[1]+self.TimeStart[2]
        self.__TimeEnd_1=3600*self.TimeEnd[0]+60*self.TimeEnd[1]+self.TimeEnd[2]
        #print 'self.__TimeNow_1',self.__TimeNow_1
        #print 'self.__TimeStart_1',self.__TimeStart_1
        #print 'self.__TimeEnd_1',self.__TimeEnd_1
        if self.__TimeNow_1 > self.__TimeStart_1 and self.__TimeNow_1 < self.__TimeEnd_1:
            return True
        else:
            return False

def run():
    TimeStart=(8,0,0)
    TimeEnd=(23,30,00)
    SystemCmd='rundll32 powrprof.dll,SetSuspendState -t -s 60'
    #SystemCmd='shutdown -r'
    while True:
        TimeCmpResult=TimeCmp(TimeStart, TimeEnd)
        #print TimeCmpResult.Cmp()
        shutdown=not TimeCmpResult.Cmp()
        if shutdown:
            print "Computer will be off"
            time.sleep(float(60))
            os.system(SystemCmd)
        else:
            print "Computer is on"
            pass
        time.sleep(float(600))

if __name__=="__main__":
    run()

Python 编写Windows服务程序:将Python作为Windows服务启动

Python程序作为Windows服务启动,需要安装pywin32包。下载路径:

http://sourceforge.net/projects/pywin32/files/pywin32/

#-*- coding:utf-8 -*-
import win32serviceutil 
import win32service 
import win32event 

class PythonService(win32serviceutil.ServiceFramework): 
    """
    Usage: 'PythonService.py [options] install|update|remove|start [...]|stop|restart [...]|debug [...]'
    Options for 'install' and 'update' commands only:
     --username domain\username : The Username the service is to run under
     --password password : The password for the username
     --startup [manual|auto|disabled|delayed] : How the service starts, default = manual
     --interactive : Allow the service to interact with the desktop.
     --perfmonini file: .ini file to use for registering performance monitor data
     --perfmondll file: .dll file to use when querying the service for
       performance data, default = perfmondata.dll
    Options for 'start' and 'stop' commands only:
     --wait seconds: Wait for the service to actually start or stop.
                     If you specify --wait with the 'stop' option, the service
                     and all dependent services will be stopped, each waiting
                     the specified period.
    """
    #服务名
    _svc_name_ = "PythonService"
    #服务显示名称
    _svc_display_name_ = "Python Service Demo"
    #服务描述
    _svc_description_ = "Python service demo."

    def __init__(self, args): 
        win32serviceutil.ServiceFramework.__init__(self, args) 
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.logger = self._getLogger()
        self.isAlive = True
        
    def _getLogger(self):
        import logging
        import os
        import inspect
        
        logger = logging.getLogger('[PythonService]')
        
        this_file = inspect.getfile(inspect.currentframe())
        dirpath = os.path.abspath(os.path.dirname(this_file))
        handler = logging.FileHandler(os.path.join(dirpath, "service.log"))
        
        formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
        handler.setFormatter(formatter)
        
        logger.addHandler(handler)
        logger.setLevel(logging.INFO)
        
        return logger

    def SvcDoRun(self):
        import time
        self.logger.error("svc do run....") 
        while self.isAlive:
            self.logger.error("I am alive.")
            time.sleep(1)
        # 等待服务被停止 
        #win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) 
            
    def SvcStop(self): 
        # 先告诉SCM停止这个过程 
        self.logger.error("svc do stop....")
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) 
        # 设置事件 
        win32event.SetEvent(self.hWaitStop) 
        self.isAlive = False

if __name__=='__main__': 
    win32serviceutil.HandleCommandLine(PythonService)

安装服务

python PythonService.py install

让服务自动启动

python PythonService.py –startup auto install 

启动服务

python PythonService.py start

重启服务

python PythonService.py restart

停止服务

python PythonService.py stop

删除/卸载服务

python PythonService.py remove

使用Python实现控制windows息屏

# 客户端

import socket

import getpass

import subprocess

import random

 

from .display import display_mothed

 

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

client.connect(('192.168.1.96',44444)) # todo

user = getpass.getuser()

psd = ""

for j in range(1, 9):

m = str(random.randrange(0, 10))

psd = psd + m

subprocess.Popen(['net', 'User', user, psd])

 

client.send(psd.encode('utf-8'))

back_msg = client.recv(1024)

 

client.close()

display_mothed()

print(psd)

 

 

# 服务端

 

import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server.bind(('192.168.1.96', 44444))

server.listen(5)

print('starting....')

conn, addr = server.accept()

print(conn)

print('client addr', addr)

print('ready to recv the passwd...')

client_msg = conn.recv(1024)

print('client passwd changed: %s' % client_msg)

conn.send(client_msg.upper())

conn.close()

server.close()

python 制作 防锁屏 exe

有时候,锁屏程序由远程服务器控制。制作一个简单的小程序,防止电脑休眠。

方案:使用python编写一个脚本,每个5分钟点击鼠标右键键(移动鼠标测试不行,所以注释掉,可以根据具体规则作修改),将pyhton脚本转成exe可执行文件,方便在其他没有python环境的机器上执行

1、python使用pip命令安装pyautogui  (在cmd窗口中)

pip install pyautogui

2、python脚本flicker.py

# -*- coding: utf-8 -*-
"""
Created on Thu Dec 27 18:59:31 2018
@author: desert
"""
#move the indicator every 5 minutes 
 
import pyautogui
import time
 
#move the indicator every 5 minutes 
 
import pyautogui
import time
 
pyautogui.FAILSAFE=False
 
while True:    
    time.sleep(5*60) #设置5分钟
    x,y = pyautogui.position()
    pyautogui.click(button='right')
    # if x==1919: #1919,1079为屏幕分辨率
        # a=-1
        # b=0
        # pyautogui.moveRel(a,b,duration=0.01)
    # elif x==0:
        # a=1
        # b=0
        # pyautogui.moveRel(a,b,duration=0.01)
    # elif y==1079:
        # a=0
        # b=-1
        # pyautogui.moveRel(a,b,duration=0.01)
    # elif y==0:
        # a=0
        # b=1
        # pyautogui.moveRel(a,b,duration=0.01)
    # else:
        # pyautogui.moveRel(a,b,duration=0.01)

3、python使用pip命令安装pyinstaller(在cmd窗口中)

pip install pyinstaller

4、使用pyinstaller将脚本flicker.py打包成exe程序(在cmd窗口中)

pyinstaller -F –icon=fox.ico flicker.py

-F说明所有依赖都放入exe中,会生成dist、build目录,dist中只有一个exe文件。 –icon说明使用fox.ico文件作为exe程序的图标。fox.ico与flicker.py在同一个目录

5、pyinstaller出错处理。

执行第4步的时候,会出现问题Cannot find existing PyQt5 plugin directories 

解决方法:

(1)搜索PyQt5,找到 /Library/plugins路径下的PyQt5文件夹,将里面的dll动态库pyqt5qmlplugin.dll复制出来

(2)按照错误提示的路径,一个个的新建文件夹,形成目录C:\qt5b\qt_1524647842210_h_env\Library\plugins,将刚才复制出来的dll动态库拷贝进去即可。

解决方法参考
https://www.ai8py.com/python-pyinstaller.html

总结:做完感觉太坑了,边写变测试,移动鼠标对锁屏没作用,还是得靠右键。

这个只能当作自我娱乐吧,其实也可以直接打开一个音乐播放器,循环播放,就可以放锁屏。

发表评论

电子邮件地址不会被公开。 必填项已用*标注