search
HomeBackend DevelopmentPython Tutorialpython version of imitation windows scheduled task tool_python

这篇文章主要介绍了python版本的仿windows计划任务工具,计划任务工具根据自己设定的具体时间,频率,命令等属性来规定所要执行的计划,当然功能不是很全大家可以补充

计划任务工具-windows

计划任务工具根据自己设定的具体时间,频率,命令等属性来规定所要执行的计划。

效果图

代码

# -*- coding: utf-8 -*-

"""
Module implementing App.
"""

from PyQt4.QtGui import QMainWindow
from PyQt4.QtCore import pyqtSignature
import time,os
import QtUtil
import shutil
import time

from v.Ui_App import Ui_MainWindow

class App(QMainWindow, Ui_MainWindow):
  """
  Class documentation goes here.
  """
  def __init__(self, parent = None):
    """
    Constructor
    """
    QMainWindow.__init__(self, parent)
    self.setupUi(self)
    
    # 创建'res/command'文件夹
    if os.path.exists('res/command'):
      pass
    else:
      os.mkdir('res/command')
    
#     self.startDate.textFromDateTime()
  
  
  @pyqtSignature("")
  def on_run_btn_clicked(self):
    """
            创建任务.
    """   
    
    # 在查询栏显示的内容
    cmd = self.taskRun.toPlainText()
    # 构建'res/command/01.txt'文件
    if not os.path.exists('res/command/01.txt'):
      m = open('res/command/01.txt','w')
      m.close()
    p = str(self.modifier.text())
    # 判断日期是否正确
    if self.endDate.text() <= self.startDate.text():
      QtUtil.showOkDialog(self, u&#39;日期出错&#39;, u&#39;结束日期要大于开始日期&#39;)
    
    elif not p.isdigit():
      QtUtil.showOkDialog(self, u&#39;频率出错&#39;, u&#39;运行频率必须为整数&#39;)
      
    else:
      # 如果任务条件不完整,则创建失败
      if self.taskName.text()==&#39;&#39; or self.modifier.text()==&#39;&#39; or cmd==&#39;&#39;:
        QtUtil.showOkDialog(self, u&#39;创建失败&#39;, u&#39;任务内容缺失&#39;)
      else:
        # 读取&#39;res/command&#39;下所有文件的文件名到filename
        for root, dirs, files in os.walk(&#39;res/command&#39;):
          for file in files:
            filename = open(&#39;res/filename.txt&#39;,&#39;a&#39;)
            filename.write(&#39;/&#39;)
  #           filename.truncate()
            filename.write(str(file))
            filename.close()
            filename1 = open(&#39;res/filename.txt&#39;)
            fn = filename1.read()
            filename1.close()
        print fn
        print &#39;/&#39; + str(self.taskName.text()) + &#39;.cmd&#39;
        # 如果任务名在filename中能找到,则说明任务已经存在
        if &#39;/&#39; + str(self.taskName.text()) + &#39;.cmd&#39; in fn:
          QtUtil.showOkDialog(self, u&#39;创建失败&#39;, u&#39;任务已存在&#39;)
           
        else:
          
          # 任务内容
          if self.schedule.currentText() == &#39;monthly&#39;:
            print &#39;monthly&#39;
            run = &#39;schtasks /create /tn &#39;+ self.taskName.text() + &#39; /tr &#39;+os.getcwd()+&#39;/res/command/&#39;+self.taskName.text()+&#39;.bat /sc &#39; + self.schedule.currentText() + &#39; /d &#39; +self.modifier.text() + &#39; /m &#39; + self.month.currentText() + &#39; /st &#39; + self.timeEdit.text() + &#39; /sd &#39; + self.startDate.text() + &#39; /ed &#39; + self.endDate.text()
          elif self.schedule.currentText() == &#39;once&#39;:
            print &#39;once&#39;
            run = &#39;schtasks /create /tn &#39;+ self.taskName.text() + &#39; /tr &#39;+os.getcwd()+&#39;/res/command/&#39;+self.taskName.text()+&#39;.bat /sc &#39; + self.schedule.currentText() + &#39; /st &#39; + self.timeEdit.text() + &#39; /sd &#39; + self.startDate.text() 
            if self.startDate.text() < time.strftime(&#39;%Y/%m/%d&#39;) or (self.timeEdit.text() <= time.strftime(&#39;%H:%M:%S&#39;) and self.startDate.text() == time.strftime(&#39;%Y/%m/%d&#39;)) :
              QtUtil.showOkDialog(self, u&#39;时间错误&#39;, u&#39;设置时间早于当前时间&#39;)
              return
          else: 
            print &#39;not monthly&#39;
            run = &#39;schtasks /create /tn &#39;+ self.taskName.text() + &#39; /tr &#39;+os.getcwd()+&#39;/res/command/&#39;+self.taskName.text()+&#39;.bat /sc &#39; + self.schedule.currentText() + &#39; /mo &#39; +self.modifier.text() + &#39; /st &#39; + self.timeEdit.text() + &#39; /sd &#39; + self.startDate.text() + &#39; /ed &#39; + self.endDate.text()
          
          # 创建命令文件
          fd = open(&#39;res/command/&#39;+self.taskName.text()+&#39;.bat&#39;,&#39;w&#39;)
          fd.write(cmd)
          fd.close()
          
          # 创建任务文件
          f = open(&#39;res/command/&#39;+self.taskName.text()+&#39;.cmd&#39;,&#39;w&#39;)
          f.write(run)
          f.close()
          # 创建任务
          os.system(os.getcwd()+&#39;\\res\command\\&#39;+str(self.taskName.text())+&#39;.cmd&#39;)
          QtUtil.showOkDialog(self, u&#39;创建成功&#39;, u&#39;创建成功&#39;)
  @pyqtSignature("")
  def on_delete_btn_clicked(self):
    """
            删除任务.
    """
    # 强制删除删除框内任务
    x=os.system(&#39;schtasks /delete /tn &#39;+str(self.taskDelete.text()).decode(&#39;gbk&#39;)+&#39; /f&#39;)
    # 如果已经任务已经删除,则报任务不存在
    if x==1:
      QtUtil.showOkDialog(self, u&#39;删除失败&#39;, u&#39;任务名错误或不存在该任务&#39;)
    else:
      os.remove(&#39;res/filename.txt&#39;)
      
      
      if os.path.exists(&#39;res/command/&#39;+self.taskDelete.text()+&#39;.cmd&#39;):
        os.remove(&#39;res/command/&#39;+str(self.taskDelete.text())+&#39;.bat&#39;)
        os.remove(&#39;res/command/&#39;+str(self.taskDelete.text())+&#39;.cmd&#39;)
        
      # 读取&#39;res/command&#39;下所有文件的文件名到filename
      for root, dirs, files in os.walk(&#39;res/command&#39;):
        for file in files:
          filename = open(&#39;res/filename.txt&#39;,&#39;a&#39;)
          filename.write(&#39;/&#39;)
#           filename.truncate()
          filename.write(str(file))
          filename.close()
          filename1 = open(&#39;res/filename.txt&#39;)
          fn = filename1.read()
          filename1.close()
      # 删除任务,并删除命令文件与任务文件
      QtUtil.showOkDialog(self, u&#39;删除成功&#39;, u&#39;删除成功&#39;) 
      
  @pyqtSignature("")
  def on_query_btn_clicked(self):
    """
            查询任务.
    """
    # 调整 936 为 437 美国编码,才可运行
    os.system(&#39;chcp 437&#39;)
    # 查询任务
    os.system(&#39;schtasks /query&#39;)
    # 在生成新log文件前先删除以前的log文件
    if os.path.exists(&#39;res/log.txt&#39;):
      os.remove(&#39;res/log.txt&#39;)
    
    # 遍历&#39;res/command&#39;的所有文件,将所有文件内容复制到log文件中
    for root, dirs, files in os.walk(&#39;res/command&#39;):
      for file in files:
        dir = str(root)+&#39;/&#39;+str(file)
        f = open(dir,&#39;r&#39;)
        scripts = f.read()
        new_path_filename = &#39;res/log.txt&#39;
        
        f = open(new_path_filename, &#39;a&#39;)
        f.write(scripts) 
        f.write(&#39;\n&#39;)
        f.close()
    # 读取log文件
    if os.path.exists(&#39;res/log.txt&#39;):
      fd=open(&#39;res/log.txt&#39;)
      info = fd.read()
      fd.close()
      # 在查询窗口显示log文件内容
      self.taskQuery.setText(str(info))
    else:
      QtUtil.showOkDialog(self, u&#39;失败&#39;, u&#39;不存在任务&#39;)
  
  @pyqtSignature("")
  def on_delall_btn_clicked(self):
    """
            清空任务.
    """
    os.system(&#39;schtasks /delete /tn * /f&#39;)
    if os.path.exists(&#39;res/log.txt&#39;):
      os.remove(&#39;res/log.txt&#39;)
    if os.path.exists(&#39;res/filename.txt&#39;):  
      os.remove(&#39;res/filename.txt&#39;)
    shutil.rmtree(&#39;res/command&#39;)
    os.mkdir(&#39;res/command&#39;)
    QtUtil.showOkDialog(self, u&#39;成功&#39;, u&#39;任务清空&#39;)

“任务名称”填写任务的名字,计划类型选择时间,频率填写次数,在计划类型中除了monthly之外的其他类型都填写频率,monthly时日期填写日期号数,月份也只在选择monthly时候需要选择,其他时候不用选择,月份中*号问任意月,接着填写开始时间、开始日期、结束日期,结束日期要大于开始日期,最后填写所要执行的命令,则任务创建成功。,创建任务后随时可以查阅任务,点击查询任务即可,删除任务只要填上要删除的任务名称,点击删除任务即可,清空任务为删除所有任务。



The above is the detailed content of python version of imitation windows scheduled task tool_python. 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
Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

For loop and while loop in Python: What are the advantages of each?For loop and while loop in Python: What are the advantages of each?May 13, 2025 am 12:01 AM

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

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 Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.