Python script for timed off NetEase cloud Music PC Client

Source: Internet
Author: User
Tags locale python script

This article focuses on how to use Python to turn off programs running on Windows after a specified number of seconds (this program takes NetEase cloud music for example). The background of this article is that the PC client who discovered NetEase cloud music last night did not have a timed shutdown function, and could use Python to write a simple script to close such a scheduled task on a timed basis. After the improvement, you can do some useful extensions for the daily operation of dimension.

Why use Python to do this?

Is it not possible to do this with CMD, scheduled tasks, or batch processing? If you ignore the process and look at the results, it may be easier and easier to do so, but with Python you can get a lot of benefits from the process and the results in two ways:

    1. Can bring practiced hand, practice makes perfect, and many things don't forget

    2. Control program behavior more flexible, want to output what to output what, want to expand the function can extend the function, such as write log and so on

    3. Portability and reusability are good, and Linux and Mac OSX can also be used

How the script works:

1. Use Python's built-in module Sched to implement scheduled tasks

2. Using the Psutil module for enumeration and kill processes

3. Parallel execution of two blocking tasks using the thread module

The knowledge that this script involves:

    1. Get system language default encoding

    2. Enumeration and kill processes

    3. Gets the user name of the current user

    4. Implementing the Countdown function

    5. Implementing the Scheduled Tasks feature

    6. Python multithreaded execution

Operating environment and how to use:

    1. Python 2.7

    2. Psutil

    3. Run this script directly with Python

    4. Where you can modify the time (after a few seconds) and the name of the process in the __main__ of the script

Operation Result:

This is set to 10s after the run of NetEase cloud music is turned off

650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M01/8F/A1/wKiom1jnLsPB27zQAAJY8Y_udxY871.jpg "title=" Python timed task "alt=" Wkiom1jnlspb27zqaajy8y_udxy871.jpg "/>

Description

The first line shows the time of the current runtime;

The second row shows the current time and the remaining hours, minutes, and seconds in real time;

Lines 3rd, 4, 5, 6 indicate that the process has been found and killed;

The last two lines are printed at the end of the time and exit information;

Script content:

The script can be obtained from the Linuxbashshellscriptforops project on GitHub and gets the update and bug fix versions.

https://github.com/DingGuodong/LinuxBashShellScriptForOps/blob/master/projects/WindowsSystemOps/System/pyScheduleTask.py

The script reads as follows:

#!/usr/bin/python# encoding: utf-8# -*- coding: utf8 -*-"" "Created by  pycharm.file:                linuxbashshellscriptforops:pyscheduletask.pyuser:                guodongcreate date:        2017/4/ 6create time:        22:33  "" "# https://docs.python.org /2/library/sched.htmlimport threadingimport schedimport timeimport sysimport  Localeimport codecsdef get_system_encoding ():     "" "    The  encoding of the default system locale but falls back to  the given    fallback encoding if the encoding is  unsupported by python or could    not be determined.  see tickets # 10335 and  #5846      ""     try:         encoding = locale.getdefaultlocale () [1] or  ' ASCII '          codecs.lookup (encoding)     except LookupError:         encoding =  ' ASCII '     return  Encodingdefault_locale_encoding = get_system_encoding () def shutdown_neteasecloudmusic (name):     # define NetEaseCloudMusic process name     Processnametokill = name    print    import psutil     import sys    # learn from getpass.getuser ()     def getusER ():         "" "get the username from the  Environment or password database.        first try  various environment variables, then the password         database.  This works on Windows as long as  username is set.         "" "         import os        for username in   (' LOGNAME ',  ' USER ',  ' LNAME ',  ' USERNAME '):             user = os.environ.get (username)              if user:                  Return user    currentusername = getuser ()     if  Processnametokill in [x.name ()  for x in psutil.process_iter ()]:         print  "[i] process \"%s\ " is found!"  % ProcessNameToKill    else:         print  "[e] process \"%s\ " is not running!"  % processnametokill        sys.exit (1)      for process in psutil.process_iter ():         if  process.name ()  == ProcessNameToKill:             try:                 # root user can only kill its process, but can not kill other users process                 if process.username (). EndsWith ( CurrentUserName):                     process.kill ()                      print  "[i] process \"%s (pid=%s) \ " is  killed successfully! "  %  (Process.name (),  process.pid)              except Exception as e:                 print edef display_countdown (sec):     def  countdown (secs):         "" "      & Nbsp; blocking process 1        :p aram secs:  seconds, int        :return:          "" "        current_time = time.strftime ("%Y-%m-% D %h:%m:%s %z "). Decode (default_locale_encoding). Encode (" Utf-8 ")          print  "time current: %s"  % current_time         while secs:            now  = time.strftime ("%y-%m-%d %h:%m:%s %z"). Decode (default_locale_encoding). Encode ("Utf-8")             hours, seconds = divmod (secs, 3600)             minutes, seconds  = divmod (SECONDS, 60)             clock_format =   ' {: 02d}:{:02d}:{:02d} '. Format (hours, minutes, seconds)              sys.stdout.write (' \rtime now: %s time left: %s '  %  (Now, clock_format)              Sys.stdout.flush ()             time.sleep (1)              secs -= 1    #  set a human readable timer here, such as display how  Much time left to shutdown    countdown (int (sec)) Def display_ Scheduler (name):     "" "    blocking process 2     :return:     "" "    s = sched.scheduler (time.time, time.sleep)      s.enter (10, 1, shutdown_neteasecloudmusic,  (name))      S.run ()     now = time.strftime ("%y-%m-%d %h:%m:%s %z"). Decode (DEFAULT_ locale_encoding). Encode ("Utf-8")     print  "Time finished: %s\ngood bye !"  % nowif __name__ ==  ' __main__ ':     seconds_to_shutdown =  10    process_name_to_shutdown =  "Cloudmusic.exe"      Threadingpool = list ()     threading_1 = threading. Thread (target=display_countdown, args= (Seconds_to_shutdown,))     threading_2 =  threading. Thread (target=display_scheduler, args= (Process_name_to_shutdown,))      Threadingpool.append (threading_1)      threadingpool.append (threading_2)     for thread in  Threadingpool:        thread.setdaemon (False)          thread.start ()     thread.join ()

Tag:python scheduled task, Python timed task, Python sched

--end--

This article is from "Communication, My Favorites" blog, please make sure to keep this source http://dgd2010.blog.51cto.com/1539422/1913818

Python script for timed off NetEase cloud Music PC Client

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.