testing/mozbase/docs/mozprocess.rst

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

     1 :mod:`mozprocess` --- Launch and manage processes
     2 =================================================
     4 Mozprocess is a process-handling module that provides some additional
     5 features beyond those available with python's subprocess:
     7 * better handling of child processes, especially on Windows
     8 * the ability to timeout the process after some absolute period, or some
     9   period without any data written to stdout/stderr
    10 * the ability to specify output handlers that will be called
    11   for each line of output produced by the process
    12 * the ability to specify handlers that will be called on process timeout
    13   and normal process termination
    15 Running a process
    16 -----------------
    18 mozprocess consists of two classes: ProcessHandler inherits from ProcessHandlerMixin.
    20 Let's see how to run a process.
    21 First, the class should be instanciated with at least one argument which is a command (or a list formed by the command followed by its arguments).
    22 Then the process can be launched using the *run()* method.
    23 Finally the *wait()* method will wait until end of execution.
    25 .. code-block:: python
    27     from mozprocess import processhandler
    29     # under Windows replace by command = ['dir', '/a']
    30     command = ['ls', '-l']
    31     p = processhandler.ProcessHandler(command)
    32     print("execute command: %s" % p.commandline)
    33     p.run()
    34     p.wait()
    36 Note that using *ProcessHandler* instead of *ProcessHandlerMixin* will print the output of executed command. The attribute *commandline* provides the launched command.
    38 Collecting process output
    39 -------------------------
    41 Let's now consider a basic shell script that will print numbers from 1 to 5 waiting 1 second between each.
    42 This script will be used as a command to launch in further examples.
    44 **proc_sleep_echo.sh**:
    46 .. code-block:: sh
    48     #!/bin/sh
    50     for i in 1 2 3 4 5
    51     do
    52         echo $i
    53         sleep 1
    54     done
    56 If you are running under Windows, you won't be able to use the previous script (unless using Cygwin).
    57 So you'll use the following script:
    59 **proc_sleep_echo.bat**:
    61 .. code-block:: bat
    63     @echo off
    64     FOR %%A IN (1 2 3 4 5) DO (
    65         ECHO %%A
    66         REM if you have TIMEOUT then use it instead of PING
    67         REM TIMEOUT /T 1 /NOBREAK
    68         PING -n 2 127.0.0.1 > NUL
    69     )
    71 Mozprocess allows the specification of custom output handlers to gather process output while running.
    72 ProcessHandler will by default write all outputs on stdout. You can also provide (to ProcessHandler or ProcessHandlerMixin) a function or a list of functions that will be used as callbacks on each output line generated by the process.
    74 In the following example the command's output will be stored in a file *output.log* and printed in stdout:
    76 .. code-block:: python
    78     import sys
    79     from mozprocess import processhandler
    81     fd = open('output.log', 'w')
    83     def tostdout(line):
    84         sys.stdout.write("<%s>\n" % line)
    86     def tofile(line):
    87         fd.write("<%s>\n" % line)
    89     # under Windows you'll replace by 'proc_sleep_echo.bat'
    90     command = './proc_sleep_echo.sh'
    91     outputs = [tostdout, tofile]
    93     p = processhandler.ProcessHandlerMixin(command, processOutputLine=outputs)
    94     p.run()
    95     p.wait()
    97     fd.close()
    99 The process output can be saved (*obj = ProcessHandler(..., storeOutput=True)*) so as it is possible to request it (*obj.output*) at any time. Note that the default value for *stroreOutput* is *True*, so it is not necessary to provide it in the parameters.
   101 .. code-block:: python
   103     import time
   104     import sys
   105     from mozprocess import processhandler
   107     command = './proc_sleep_echo.sh' # Windows: 'proc_sleep_echo.bat'
   109     p = processhandler.ProcessHandler(command, storeOutput=True)
   110     p.run()
   111     for i in xrange(10):
   112         print(p.output)
   113         time.sleep(0.5)
   114     p.wait()
   116 In previous example, you will see the *p.output* list growing.
   118 Execution
   119 ---------
   121 Status
   122 ``````
   124 It is possible to query the status of the process via *poll()* that will return None if the process is still running, 0 if it ended without failures and a negative value if it was killed by a signal (Unix-only).
   126 .. code-block:: python
   128     import time
   129     import signal
   130     from mozprocess import processhandler
   132     command = './proc_sleep_echo.sh'
   133     p = processhandler.ProcessHandler(command)
   134     p.run()
   135     time.sleep(2)
   136     print("poll status: %s" % p.poll())
   137     time.sleep(1)
   138     p.kill(signal.SIGKILL)
   139     print("poll status: %s" % p.poll())
   141 Timeout
   142 ```````
   144 A timeout can be provided to the *run()* method. If the process last more than timeout seconds, it will be stopped.
   146 After execution, the property *timedOut* will be set to True if a timeout was reached.
   148 It is also possible to provide functions (*obj = ProcessHandler[Mixin](..., onTimeout=functions)*) that will be called if the timeout was reached.
   150 .. code-block:: python
   152     from mozprocess import processhandler
   154     def ontimeout():
   155         print("REACHED TIMEOUT")
   157     command = './proc_sleep_echo.sh' # Windows: 'proc_sleep_echo.bat'
   158     functions = [ontimeout]
   159     p = processhandler.ProcessHandler(command, onTimeout=functions)
   160     p.run(timeout=2)
   161     p.wait()
   162     print("timedOut = %s" % p.timedOut)
   164 By default the process will be killed on timeout but it is possible to prevent this by setting *kill_on_timeout* to *False*.
   166 .. code-block:: python
   168     p = processhandler.ProcessHandler(command, onTimeout=functions, kill_on_timeout=False)
   169     p.run(timeout=2)
   170     p.wait()
   171     print("timedOut = %s" % p.timedOut)
   173 In this case, no output will be available after the timeout, but the process will still be running.
   175 Waiting
   176 ```````
   178 It is possible to wait until the process exits as already seen with the method *wait()*, or until the end of a timeout if given. Note that in last case the process is still alive after the timeout.
   180 .. code-block:: python
   182     command = './proc_sleep_echo.sh' # Windows: 'proc_sleep_echo.bat'
   183     p = processhandler.ProcessHandler(command)
   184     p.run()
   185     p.wait(timeout=2)
   186     print("timedOut = %s" % p.timedOut)
   187     p.wait()
   189 Killing
   190 ```````
   192 You can request to kill the process with the method *kill*. f the parameter "ignore_children" is set to False when the process handler class is initialized, all the process's children will be killed as well.
   194 Except on Windows, you can specify the signal with which to kill method the process (e.g.: *kill(signal.SIGKILL)*).
   196 .. code-block:: python
   198     import time
   199     from mozprocess import processhandler
   201     command = './proc_sleep_echo.sh' # Windows: 'proc_sleep_echo.bat'
   202     p = processhandler.ProcessHandler(command)
   203     p.run()
   204     time.sleep(2)
   205     p.kill()
   207 End of execution
   208 ````````````````
   210 You can provide a function or a list of functions to call at the end of the process using the initilization parameter *onFinish*.
   212 .. code-block:: python
   214     from mozprocess import processhandler
   216     def finish():
   217         print("Finished!!")
   219     command = './proc_sleep_echo.sh' # Windows: 'proc_sleep_echo.bat'
   221     p = processhandler.ProcessHandler(command, onFinish=finish)
   222     p.run()
   223     p.wait()
   225 Child management
   226 ----------------
   228 Consider the following scripts:
   230 **proc_child.sh**:
   232 .. code-block:: sh
   234     #!/bin/sh
   235     for i in a b c d e
   236     do
   237         echo $i
   238         sleep 1
   239     done
   241 **proc_parent.sh**:
   243 .. code-block:: sh
   245     #!/bin/sh
   246     ./proc_child.sh
   247     for i in 1 2 3 4 5 
   248     do
   249         echo $i
   250         sleep 1
   251     done
   253 For windows users consider: 
   255 **proc_child.bat**:
   257 .. code-block:: bat
   259     @echo off
   260     FOR %%A IN (a b c d e) DO (
   261         ECHO %%A
   262         REM TIMEOUT /T 1 /NOBREAK
   263         PING -n 2 127.0.0.1 > NUL
   264     )
   266 **proc_parent.bat**:
   268 .. code-block:: bat
   270     @echo off
   271     call proc_child.bat
   272     FOR %%A IN (1 2 3 4 5) DO (
   273         ECHO %%A
   274         REM TIMEOUT /T 1 /NOBREAK
   275         PING -n 2 127.0.0.1 > NUL
   276     )
   278 For processes that launch other processes, mozprocess allows you to get child running status, wait for child termination, and kill children.
   280 Ignoring children
   281 `````````````````
   283 By default the *ignore_children* option is False. In that case, killing the main process will kill all its children at the same time.
   285 .. code-block:: python
   287     import time
   288     from mozprocess import processhandler
   290     def finish():
   291         print("Finished")
   293     command = './proc_parent.sh'
   294     p = processhandler.ProcessHandler(command, ignore_children=False, onFinish=finish)
   295     p.run()
   296     time.sleep(2)
   297     print("kill")
   298     p.kill()
   300 If *ignore_children* is set to *True*, killing will apply only to the main process that will wait children end of execution before stoping (join).
   302 .. code-block:: python
   304     import time
   305     from mozprocess import processhandler
   307     def finish():
   308         print("Finished")
   310     command = './proc_parent.sh'
   311     p = processhandler.ProcessHandler(command, ignore_children=True, onFinish=finish)
   312     p.run()
   313     time.sleep(2)
   314     print("kill")
   315     p.kill()
   317 API Documentation
   318 -----------------
   320 .. module:: mozprocess
   321 .. autoclass:: ProcessHandlerMixin
   322    :members: __init__, timedOut, commandline, run, kill, processOutputLine, onTimeout, onFinish, wait
   323 .. autoclass:: ProcessHandler
   324    :members:

mercurial