##// END OF EJS Templates
remove nose from test_background_jobs
remove nose from test_background_jobs

File last commit:

r26419:7663c521
r26723:f03bb325
Show More
_process_common.py
210 lines | 6.8 KiB | text/x-python | PythonLexer
Fernando Perez
Fully refactored subprocess handling on all platforms....
r2908 """Common utilities for the various process_* implementations.
This file is only meant to be imported by the platform-specific implementations
of subprocess utilities, and it contains tools that are common to all of them.
"""
#-----------------------------------------------------------------------------
Matthias BUSSONNIER
update copyright to 2011/20xx-2011...
r5390 # Copyright (C) 2010-2011 The IPython Development Team
Fernando Perez
Fully refactored subprocess handling on all platforms....
r2908 #
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import subprocess
Jörgen Stenarson
Moving posix version of arg_split to _process_common.
r5537 import shlex
Fernando Perez
Fully refactored subprocess handling on all platforms....
r2908 import sys
Pavol Juhas
Use the default shell to capture shell output....
r22413 import os
Fernando Perez
Fully refactored subprocess handling on all platforms....
r2908
Thomas Kluyver
Start using py3compat module.
r4731 from IPython.utils import py3compat
Fernando Perez
Fully refactored subprocess handling on all platforms....
r2908 #-----------------------------------------------------------------------------
# Function definitions
#-----------------------------------------------------------------------------
def read_no_interrupt(p):
"""Read from a pipe ignoring EINTR errors.
This is necessary because when reading from pipes with GUI event loops
running in the background, often interrupts are raised that stop the
command from completing."""
import errno
try:
return p.read()
Matthias BUSSONNIER
conform to pep 3110...
r7787 except IOError as err:
Fernando Perez
Fully refactored subprocess handling on all platforms....
r2908 if err.errno != errno.EINTR:
raise
def process_handler(cmd, callback, stderr=subprocess.PIPE):
"""Open a command in a shell subprocess and execute a callback.
This function provides common scaffolding for creating subprocess.Popen()
calls. It creates a Popen object and then calls the callback with it.
Parameters
----------
Thomas Kluyver
Allow process_handler to accept a list of arguments
r13738 cmd : str or list
Matthias Bussonnier
reformat docstring in IPython utils
r26419 A command to be executed by the system, using :class:`subprocess.Popen`.
If a string is passed, it will be run in the system shell. If a list is
passed, it will be used directly as arguments.
Fernando Perez
Fully refactored subprocess handling on all platforms....
r2908 callback : callable
Matthias Bussonnier
reformat docstring in IPython utils
r26419 A one-argument function that will be called with the Popen object.
Fernando Perez
Fully refactored subprocess handling on all platforms....
r2908 stderr : file descriptor number, optional
Matthias Bussonnier
reformat docstring in IPython utils
r26419 By default this is set to ``subprocess.PIPE``, but you can also pass the
value ``subprocess.STDOUT`` to force the subprocess' stderr to go into
the same file descriptor as its stdout. This is useful to read stdout
and stderr combined in the order they are generated.
Fernando Perez
Fully refactored subprocess handling on all platforms....
r2908
Returns
-------
The return value of the provided callback is returned.
"""
sys.stdout.flush()
sys.stderr.flush()
Fernando Perez
Rework messaging to better conform to our spec....
r2926 # On win32, close_fds can't be true when using pipes for stdin/out/err
close_fds = sys.platform != 'win32'
Pavol Juhas
Run user $SHELL only for shell commands....
r22414 # Determine if cmd should be run with system shell.
Srinivas Reddy Thatiparthy
convert string_types to str
r23037 shell = isinstance(cmd, str)
Pavol Juhas
Run user $SHELL only for shell commands....
r22414 # On POSIX systems run shell commands with user-preferred shell.
executable = None
if shell and os.name == 'posix' and 'SHELL' in os.environ:
executable = os.environ['SHELL']
p = subprocess.Popen(cmd, shell=shell,
executable=executable,
Fernando Perez
Fully refactored subprocess handling on all platforms....
r2908 stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=stderr,
Fernando Perez
Fix bug with Popen call on windows....
r2921 close_fds=close_fds)
Fernando Perez
Fully refactored subprocess handling on all platforms....
r2908
try:
out = callback(p)
except KeyboardInterrupt:
print('^C')
sys.stdout.flush()
sys.stderr.flush()
out = None
finally:
# Make really sure that we don't leave processes behind, in case the
# call above raises an exception
# We start by assuming the subprocess finished (to avoid NameErrors
# later depending on the path taken)
if p.returncode is None:
try:
p.terminate()
p.poll()
except OSError:
pass
# One last try on our way out
if p.returncode is None:
try:
p.kill()
except OSError:
pass
return out
Fernando Perez
Fix bugs in x=!cmd; we can't use pexpect at all....
r3002 def getoutput(cmd):
Julian Taylor
fix documentation and test of getoutput...
r10606 """Run a command and return its stdout/stderr as a string.
Fernando Perez
Fix bugs in x=!cmd; we can't use pexpect at all....
r3002
Parameters
----------
Thomas Kluyver
Allow process_handler to accept a list of arguments
r13738 cmd : str or list
Matthias Bussonnier
reformat docstring in IPython utils
r26419 A command to be executed in the system shell.
Fernando Perez
Fix bugs in x=!cmd; we can't use pexpect at all....
r3002
Returns
-------
Julian Taylor
fix documentation and test of getoutput...
r10606 output : str
Matthias Bussonnier
reformat docstring in IPython utils
r26419 A string containing the combination of stdout and stderr from the
Julian Taylor
fix documentation and test of getoutput...
r10606 subprocess, in whatever order the subprocess originally wrote to its
file descriptors (so the order of the information in this string is the
correct order as would be seen if running the command in a terminal).
Fernando Perez
Fix bugs in x=!cmd; we can't use pexpect at all....
r3002 """
out = process_handler(cmd, lambda p: p.communicate()[0], subprocess.STDOUT)
if out is None:
Thomas Kluyver
Start using py3compat module.
r4731 return ''
Hugo
Remove redundant Python 2 code
r24010 return py3compat.decode(out)
Fernando Perez
Fix bugs in x=!cmd; we can't use pexpect at all....
r3002
Fernando Perez
Fully refactored subprocess handling on all platforms....
r2908 def getoutputerror(cmd):
"""Return (standard output, standard error) of executing cmd in a shell.
Accepts the same arguments as os.system().
Parameters
----------
Thomas Kluyver
Allow process_handler to accept a list of arguments
r13738 cmd : str or list
Matthias Bussonnier
reformat docstring in IPython utils
r26419 A command to be executed in the system shell.
Fernando Perez
Fully refactored subprocess handling on all platforms....
r2908
Returns
-------
stdout : str
stderr : str
"""
Paul Ivanov
new util that also passes back the returncode
r11825 return get_output_error_code(cmd)[:2]
Fernando Perez
Fully refactored subprocess handling on all platforms....
r2908
Paul Ivanov
new util that also passes back the returncode
r11825 def get_output_error_code(cmd):
"""Return (standard output, standard error, return code) of executing cmd
in a shell.
Accepts the same arguments as os.system().
Parameters
----------
Thomas Kluyver
Allow process_handler to accept a list of arguments
r13738 cmd : str or list
Matthias Bussonnier
reformat docstring in IPython utils
r26419 A command to be executed in the system shell.
Paul Ivanov
new util that also passes back the returncode
r11825
Returns
-------
stdout : str
stderr : str
returncode: int
"""
out_err, p = process_handler(cmd, lambda p: (p.communicate(), p))
Fernando Perez
Fully refactored subprocess handling on all platforms....
r2908 if out_err is None:
Paul Ivanov
new util that also passes back the returncode
r11825 return '', '', p.returncode
Thomas Kluyver
Start using py3compat module.
r4731 out, err = out_err
Hugo
Remove redundant Python 2 code
r24010 return py3compat.decode(out), py3compat.decode(err), p.returncode
Jörgen Stenarson
Moving posix version of arg_split to _process_common.
r5537
MinRK
add strict flag to arg_split, to optionally ignore shlex parse errors...
r5672 def arg_split(s, posix=False, strict=True):
Jörgen Stenarson
Moving posix version of arg_split to _process_common.
r5537 """Split a command line's arguments in a shell-like manner.
This is a modified version of the standard library's shlex.split()
function, but with a default of posix=False for splitting, so that quotes
MinRK
add strict flag to arg_split, to optionally ignore shlex parse errors...
r5672 in inputs are respected.
if strict=False, then any errors shlex.split would raise will result in the
unparsed remainder being the last element of the list, rather than raising.
This is because we sometimes use arg_split to parse things other than
command-line args.
"""
Jörgen Stenarson
Moving posix version of arg_split to _process_common.
r5537
lex = shlex.shlex(s, posix=posix)
lex.whitespace_split = True
MinRK
add strict flag to arg_split, to optionally ignore shlex parse errors...
r5672 # Extract tokens, ensuring that things like leaving open quotes
# does not cause this to raise. This is important, because we
# sometimes pass Python source through this (e.g. %timeit f(" ")),
# and it shouldn't raise an exception.
# It may be a bad idea to parse things that are not command-line args
# through this function, but we do, so let's be safe about it.
Paul Ivanov
shlex shouldn't parse out comments, closes #1269
r5902 lex.commenters='' #fix for GH-1269
MinRK
add strict flag to arg_split, to optionally ignore shlex parse errors...
r5672 tokens = []
while True:
try:
Bradley M. Froehle
Apply 2to3 `next` fix....
r7847 tokens.append(next(lex))
MinRK
add strict flag to arg_split, to optionally ignore shlex parse errors...
r5672 except StopIteration:
break
except ValueError:
if strict:
raise
# couldn't parse, get remaining blob as last token
tokens.append(lex.token)
break
Srinivas Reddy Thatiparthy
remove dead code
r23104
Jörgen Stenarson
Moving posix version of arg_split to _process_common.
r5537 return tokens