search
HomeBackend DevelopmentPython TutorialUsing python scheduled shutdown windows script

Using python scheduled shutdown windows script

Mar 22, 2017 am 09:14 AM
pythonwindowsScheduled shutdown

Since I often use my laptop to share WiFi, but I don’t want my laptop to be turned on overnight (for the sake of low carbon and environmental protection ~_~!), so I have to use DOS commands to shut it down every time, which feels very troublesome. I happened to be learning Python recently, so I decided to use python to write a scheduled shutdown script:

Not much to say since the code is relatively simple, let’s go directly to the code.

Code block


# -*- coding: utf-8 -*-
"""
Created on Sat Dec 19 11:18:16 2015
@author: win7
"""
'''定时关机'''
'''脚本功能:windows下,用户按照一定格式输入关机时间,系统到指定时间自动关闭
  思路:从用户输入获取指定时间 分别以时分秒减去当前时间 最终计算得到当前时间距离指定
  时间还有多少秒 作为关机命令的时间参数
'''
'''需要用到的模块:
        os 用于执行设定的系统命令
        time 用于获取系统时间
 需要用到的命令: shutdown -s -t xxx 其中xxx为距离自动关机所用秒数,即时间参数      
        shutdown -a 取消关机计划
'''
import os,time
#获取用户指定关机时间
print u'使用说明:输入关机时间,格式如:小时:分钟 举个栗子:20:21 然后敲回车 即可  
如果想取消定时关机 再次双击打开程序 输入 off 敲回车 即可'.encode('mbcs')
#u'xxx'.encode('mbcs') 使正文字符在控制台正确显示
input_time=raw_input(u'请输入关机时间,格式如:小时:分钟 :'.encode('mbcs'))
#取消定时关机
#计划总有变化 先留条后路
if input_time == 'off':
  os.system('shutdown -a')
#输入数据检查
#由于是自用 暂时略过
#提取时分秒
h1 = int(input_time[0:2])
m1 = int(input_time[3:5])
#print h1,m1#验证获取是否正确
#获取当前系统时间
mytime = time.strftime('%H:%M:%S')
h2 = int(mytime[0:2])
m2 = int(mytime[3:5])
#print h2,m2 #验证获取是否正确
#对用户输入数据进行整理 防止出现25:76:66这样的时间数据
if h1 > 24:
  h1 = 24
  m2 = 0
if m1 > 60:
  m1 = 60
if h1<h2:
  h1 = h1 + 24  
#计算秒数
s1=(h1+(m1/60.0)-h2-(m2/60.0))*3600
print &#39;距离关机还有 %d 秒&#39; %s1
os.system(&#39;shutdown -s -t %d&#39; %s1 )

The author said

Not long after I started learning python by myself, this script was relatively crude. , many functions have not been added, such as: checking of input data, the method of processing output data is also relatively rough, and there are many poorly written places. I hope that the masters who see it can correct me.

Problems encountered in completing the script

It feels a little embarrassing to say that I made a lot of low-level mistakes in the process of writing the script. In order to avoid blushing in the future and to provide a teaching example of errors for those who are just getting started, I hereby record them all. It will be a joy for the master to read them! ~_~

1. I forgot about integer/integer = integer. The time was always wrong during the test because when I converted the minutes into hours, the number I divided was 60. This is an integer, so the results I got were all wrong. Later, I calculated the results one by one. During the output test, I realized that I was drunk

2. I forgot to convert the data type and the data obtained by raw_input() was a string. When I tested, I reported an error directly and then I remembered that I was drunk

3. Finally, there was a problem with character display. When I finished writing the script and ran it, the console displayed garbled characters. Later, I found a solution through Baidu u'xxx'.encode('mbcs')

The above is the detailed content of Using python scheduled shutdown windows script. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What data types can be stored in a Python array?What data types can be stored in a Python array?Apr 27, 2025 am 12:11 AM

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

What happens if you try to store a value of the wrong data type in a Python array?What happens if you try to store a value of the wrong data type in a Python array?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Which is part of the Python standard library: lists or arrays?Which is part of the Python standard library: lists or arrays?Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

What should you check if the script executes with the wrong Python version?What should you check if the script executes with the wrong Python version?Apr 27, 2025 am 12:01 AM

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

What are some common operations that can be performed on Python arrays?What are some common operations that can be performed on Python arrays?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

In what types of applications are NumPy arrays commonly used?In what types of applications are NumPy arrays commonly used?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

When would you choose to use an array over a list in Python?When would you choose to use an array over a list in Python?Apr 26, 2025 am 12:12 AM

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

Are all list operations supported by arrays, and vice versa? Why or why not?Are all list operations supported by arrays, and vice versa? Why or why not?Apr 26, 2025 am 12:05 AM

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.