python实现程序重启和系统重启方式

我就废话不多说了,还是直接看代码吧!

def restart_program():
  """Restarts the current program.
  Note: this function does not return. Any cleanup action (like
  saving data) must be done before calling this function."""
  python = sys.executable
  os.execl(python, python, * sys.argv)

机器重启

#!/usr/bin/python
#coding=utf-8
import time
from os import system
runing = True
while runing:
 input = raw_input('关机(s)OR重启(r)?(q退出)')
 input = input.lower()
 if input == 'q' or input =='quit':
  runing = False
  print '程序退出'
  break
 seconds = int(raw_input('请输入暂停时间(单位:秒):'))
 time.sleep(seconds)
 print '暂停时间:', seconds
 runing = False
 
 if input == 's':
  print '关机ing'
  system('halt')
 elif input == 'r':
  print '重启ing'
  system('reboot')
 else:
  print '程序错误重新输入'
  runing = True
print '程序结束~~~!'

补充知识:python一些事(重启与清屏)

当我们使用python进行计算,并且进行一系列打印之后,如果这个时候我们发现打印的内容不符合我们要求,需要重新打印,并且还不想看到以前打印的错误信息,怎么办?

答:有两种方法,1、重启。2、清屏。都能搞定我们前面提到问题。个人推荐第二种,不要问我为什么?

当然这两种方法首先都必须有循环,通过一个死循环和一个限制条件(总得让程序停下来是不是)来保证达到我们的最终目的(当然是正确信息输出的目的),如果输出符合我们想要的打印结果,就break,否则,continue。

这里的循环和限制条件就不写了(跟着你的需求走),只写重启和清屏(当然不是我自创的,肯定是从python前辈的经验学过来的)。

程序重启

def restart_program():
  """Restarts the current program.
  Note: this function does not return. Any cleanup action (like
  saving data) must be done before calling this function."""
  print('ready to restart program......')
  python = sys.executable
  os.execl(python, python, *sys.argv)

控制台清屏

os.system('cls')

在这里写这点小东西只有两个目的,第一,自己总结下,下次遇到就不懵逼了。第二、希望可以帮助一些有可能会遇到和我同样问题的人。

以上这篇python实现程序重启和系统重启方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

若文章对您有帮助,帮忙点个赞!

0
-4
发布时间 2020-04-16 12:00:26
0 条回复(回复会通过微信通知作者)
点击加载更多评论
登录 后再进行评论
(微信扫码即可登录,无需注册)