Programming Basics python: python start the application and terminate the application of the method

Today small for everyone to share a python start the application and terminate the application of the method, a good reference value, we want to help. Come and see, to follow the small series together

  1. purpose

Go to work every day, work requirements, the computer needs to boot some software every day, time off work, you need to turn off some software. A seemingly open and close is a very tedious, and thus, the script creates.

  1. surroundings

System environment:

  • win7-32 ​​bit

  • python 2.7.9

You also need to install pywin32.

pip install pywin32

  1. Scripting

Start the application script

#coding=utf-8
  
import win32api
#日报软件启动
win32api.ShellExecute(0, 'open', r'C:\Program Files\Pudding\Pudding.exe', '','',1)
  
#OA启动
win32api.ShellExecute(0, 'open', r'C:\Program Files\Tongda\ispirit\ispiritPro.exe', '','',1)
  
#QQ启动
win32api.ShellExecute(0, 'open', r'D:\QQ\Bin\QQ.exe', '','',1)
  
#......
#当然你还可以添加很多你需要启动的软件

Terminate the application script

#coding=utf-8
  
import os
  
#终止QQ软件
os.system("taskkill /F /IM QQ.exe")
  
#终止日报订餐软件
os.system("taskkill /F /IM Pudding.exe")
  
#终止OA软件
os.system("taskkill /F /IM ispiritPro.exe")
  
#......
#当然你还可以添加很多你需要终止的软件
  1. Production exe

Finally, these two scripts made into exe files, on the table, each time it is easy to use.

python call system commands, execute the command line

python call system commands way is to have more, os / command / subprocess module are ways to do

Compared to other languages ​​(landlord used language not many):

PHP: exec (), system (), the overall feeling is not good use, obstruction difficult subject

java: module function is very powerful, not to say that the function is very similar to the python's subprocess

(1) os.system

Only one sub-terminal operations system commands, but can not obtain the information return command

(2) os.popen

This method not only performs the information object also returns execution command

(3) Module Module commands

There are two commonly used methods: getoutput and getstatusoutput

(4) using subprocess module

In the final analysis subprocess most powerful, can achieve a lot of features:

For example, the project recently encountered need to call in python shell commands, but also get call information, call monitoring process, timeouts terminated, which requires the calling process is not blocked, but also interactive, found subprocess can meet, be a high

Usage (file conversion for example):

time_start = time.time()
cmd = "pdf2htmlEX --no-drm 1 --embed-css 0 --embed-image 0 --embed-font 0 --split-pages 1 --fit-width 748 --css-filename html.css --dest-dir %s --embed-external-font 0 --auto-hint 1 %s" % (html_output_folder, src_file)
  cmd_list = cmd.split(" ")
  sub2 = subprocess.Popen(cmd_list)
  i = 0
  while 1:
    ret1 = subprocess.Popen.poll(sub2)
    if ret1 == 0:
      time_end = time.time()
      time_take = int(time_end - time_start + 0.5)
      with global_value_lock:
        success_ids[param[2]] = time_take
      print sub2.pid,'end'
      break
    elif ret1 is None:
      print sub2.pid, 'running'
      if i >= max_check_time:
        time_end = time.time()
        time_take = int(time_end - time_start + 0.5)
        with global_value_lock:
          timeout_ids[param[2]] = time_take
        sub2.kill()
        log_insert("%s%s%s" % (log_dir(output_folder), os.sep, "convert_log.txt"), src_file, "Timeout_Error", 'None')
        print "*****************Timeout_Error*****************"
        break
      time.sleep(check_time)
    else:
      time_end = time.time()
      time_take = int(time_end - time_start + 0.5)
      with global_value_lock:
        converterror_ids[param[2]] = time_take
      log_insert("%s%s%s" % (log_dir(output_folder), os.sep, "convert_log.txt"), src_file, "Process_Term_Error", str(ret1))
      print sub2.pid,'term', ret1, ret1
      break
    i += 1

! ! Note: when we directly use cmd and not cmd_list, get the pid is not pdf2html from the process, but its parent, remember remember

Here are some basic usage of Popen

Popen its constructor as follows:

subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)

Args parameter may be a string or sequence type (eg: list, tuple), and the executable file for the specified process parameters. If the type is a sequence, usually the first element of the path of the executable file. We can also explicitly use executeable parameter to specify the path to the executable file. On windows operating system, Popen created by calling CreateProcess () a child process, CreateProcess takes a string parameter, if args is a sequence type, the system will by list2cmdline () function to convert a string type sequence.

Parameters bufsize: Specify the buffer. I still do not know the specific meaning of the parameters, hope all the major cattle pointing.

Parameter specifies the executable for executable programs. We set the program to run through the args parameter under normal circumstances. If the shell parameter is set to True, executable program will specify the shell to use. In windows platform, the default shell is specified by the COMSPEC environment variable.

Parameters stdin, stdout, stderr represent standard input, output, error handler program. They can be a PIPE, file descriptor or file object can also be set to None, expressed inherited from the parent process.

Preexec_fn parameter is valid only in Unix platform, is used to specify an executable objects (callable object), it will be called before the child process run.

Parameters Close_sfs: windows platform, if close_fds child process is set to True, the newly created will not inherit the parent's input, output, error pipeline. We can not close_fds set to True standard input redirection while the child process, output and error (stdin, stdout, stderr).

If the shell parameter set to true, the program will be executed through the shell.

Cwd parameter is used to set the current directory of the child process.

Env parameter type is a dictionary for the environment variable specifies the child process. If env = None, environment variables child process inherited from the parent process.

Parameters Universal_newlines: different operating systems, line breaks, the text is not the same. Such as: changing the windows represented by '/ r / n', while Linux using '/ n'. If you set this parameter to True, Python unify these line breaks as '/ n' to deal with.

Startupinfo createionflags parameters and with windows only in effect, they will be passed to the underlying CreateProcess () function, some of the attributes set for the child process, such as: priority of the appearance of the main window, processes and the like.

subprocess.PIPE

When you create an object Popen, subprocess.PIPE can initialize stdin, stdout or stderr parameters. It represents the standard sub-process communication flow.

subprocess.STDOUT

Popen When creating an object, for stderr initialization parameter indicates the error by the standard output stream.

Popen method:

Popen.poll()

For checking whether the child process has ended. Settings and return returncode property.

Popen.wait()

Wait for the child process ends. Settings and return returncode property.

Popen.communicate(input=None)

Interact with the child. Transmitting data to the stdin, stdout and read data from, or to stderr. Optional parameter specifies the input parameter sent to the child process. Communicate () returns a tuple: (stdoutdata, stderrdata). Note: If you want to send data, when creating Popen objects, parameters must be set to stdin stdin PIPE through the process. Similarly, if you want to get data from stdout and stderr, stdout and stderr must be set to PIPE.

Popen.send_signal(signal)

Send a signal to the child process.

Popen.terminate()

Stop (stop) the child process. In windows platform, which calls the Windows API TerminateProcess () to end the child process.

Popen.kill()

Kill the child process.

Popen.stdin

If you are creating Popen objects that stdin parameter is set to PIPE, Popen.stdin returns a file object for making child process to send commands. Otherwise it returns None.

Popen.stdout

If you are creating Popen objects that parameter is set to stdout PIPE, Popen.stdout returns a file object for making child process to send commands. Otherwise it returns None.

Popen.stderr

If you are creating Popen objects that parameter is set to stdout PIPE, Popen.stdout returns a file object for making child process to send commands. Otherwise it returns None.

Popen.pid

Get child process's ID.

Popen.returncode

Process of obtaining the return value. If the process is not over, return None.
Finally, we recommend a very wide python learning resource gathering, [click to enter] , here are my collection before learning experience, study notes, there is a chance of business experience, and calmed down to zero on the basis of information to project combat , we can at the bottom, leave a message, do not know to put forward, we will study together progress

Published 15 original articles · won praise 2 · views 10000 +

Guess you like

Origin blog.csdn.net/haoxun11/article/details/104908056