##// END OF EJS Templates
remove dead code
Srinivas Reddy Thatiparthy -
Show More
@@ -1,223 +1,212 b''
1 1 """Common utilities for the various process_* implementations.
2 2
3 3 This file is only meant to be imported by the platform-specific implementations
4 4 of subprocess utilities, and it contains tools that are common to all of them.
5 5 """
6 6
7 7 #-----------------------------------------------------------------------------
8 8 # Copyright (C) 2010-2011 The IPython Development Team
9 9 #
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #-----------------------------------------------------------------------------
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Imports
16 16 #-----------------------------------------------------------------------------
17 17 import subprocess
18 18 import shlex
19 19 import sys
20 20 import os
21 21
22 22 from IPython.utils import py3compat
23 23
24 24 #-----------------------------------------------------------------------------
25 25 # Function definitions
26 26 #-----------------------------------------------------------------------------
27 27
28 28 def read_no_interrupt(p):
29 29 """Read from a pipe ignoring EINTR errors.
30 30
31 31 This is necessary because when reading from pipes with GUI event loops
32 32 running in the background, often interrupts are raised that stop the
33 33 command from completing."""
34 34 import errno
35 35
36 36 try:
37 37 return p.read()
38 38 except IOError as err:
39 39 if err.errno != errno.EINTR:
40 40 raise
41 41
42 42
43 43 def process_handler(cmd, callback, stderr=subprocess.PIPE):
44 44 """Open a command in a shell subprocess and execute a callback.
45 45
46 46 This function provides common scaffolding for creating subprocess.Popen()
47 47 calls. It creates a Popen object and then calls the callback with it.
48 48
49 49 Parameters
50 50 ----------
51 51 cmd : str or list
52 52 A command to be executed by the system, using :class:`subprocess.Popen`.
53 53 If a string is passed, it will be run in the system shell. If a list is
54 54 passed, it will be used directly as arguments.
55 55
56 56 callback : callable
57 57 A one-argument function that will be called with the Popen object.
58 58
59 59 stderr : file descriptor number, optional
60 60 By default this is set to ``subprocess.PIPE``, but you can also pass the
61 61 value ``subprocess.STDOUT`` to force the subprocess' stderr to go into
62 62 the same file descriptor as its stdout. This is useful to read stdout
63 63 and stderr combined in the order they are generated.
64 64
65 65 Returns
66 66 -------
67 67 The return value of the provided callback is returned.
68 68 """
69 69 sys.stdout.flush()
70 70 sys.stderr.flush()
71 71 # On win32, close_fds can't be true when using pipes for stdin/out/err
72 72 close_fds = sys.platform != 'win32'
73 73 # Determine if cmd should be run with system shell.
74 74 shell = isinstance(cmd, str)
75 75 # On POSIX systems run shell commands with user-preferred shell.
76 76 executable = None
77 77 if shell and os.name == 'posix' and 'SHELL' in os.environ:
78 78 executable = os.environ['SHELL']
79 79 p = subprocess.Popen(cmd, shell=shell,
80 80 executable=executable,
81 81 stdin=subprocess.PIPE,
82 82 stdout=subprocess.PIPE,
83 83 stderr=stderr,
84 84 close_fds=close_fds)
85 85
86 86 try:
87 87 out = callback(p)
88 88 except KeyboardInterrupt:
89 89 print('^C')
90 90 sys.stdout.flush()
91 91 sys.stderr.flush()
92 92 out = None
93 93 finally:
94 94 # Make really sure that we don't leave processes behind, in case the
95 95 # call above raises an exception
96 96 # We start by assuming the subprocess finished (to avoid NameErrors
97 97 # later depending on the path taken)
98 98 if p.returncode is None:
99 99 try:
100 100 p.terminate()
101 101 p.poll()
102 102 except OSError:
103 103 pass
104 104 # One last try on our way out
105 105 if p.returncode is None:
106 106 try:
107 107 p.kill()
108 108 except OSError:
109 109 pass
110 110
111 111 return out
112 112
113 113
114 114 def getoutput(cmd):
115 115 """Run a command and return its stdout/stderr as a string.
116 116
117 117 Parameters
118 118 ----------
119 119 cmd : str or list
120 120 A command to be executed in the system shell.
121 121
122 122 Returns
123 123 -------
124 124 output : str
125 125 A string containing the combination of stdout and stderr from the
126 126 subprocess, in whatever order the subprocess originally wrote to its
127 127 file descriptors (so the order of the information in this string is the
128 128 correct order as would be seen if running the command in a terminal).
129 129 """
130 130 out = process_handler(cmd, lambda p: p.communicate()[0], subprocess.STDOUT)
131 131 if out is None:
132 132 return ''
133 133 return py3compat.bytes_to_str(out)
134 134
135 135
136 136 def getoutputerror(cmd):
137 137 """Return (standard output, standard error) of executing cmd in a shell.
138 138
139 139 Accepts the same arguments as os.system().
140 140
141 141 Parameters
142 142 ----------
143 143 cmd : str or list
144 144 A command to be executed in the system shell.
145 145
146 146 Returns
147 147 -------
148 148 stdout : str
149 149 stderr : str
150 150 """
151 151 return get_output_error_code(cmd)[:2]
152 152
153 153 def get_output_error_code(cmd):
154 154 """Return (standard output, standard error, return code) of executing cmd
155 155 in a shell.
156 156
157 157 Accepts the same arguments as os.system().
158 158
159 159 Parameters
160 160 ----------
161 161 cmd : str or list
162 162 A command to be executed in the system shell.
163 163
164 164 Returns
165 165 -------
166 166 stdout : str
167 167 stderr : str
168 168 returncode: int
169 169 """
170 170
171 171 out_err, p = process_handler(cmd, lambda p: (p.communicate(), p))
172 172 if out_err is None:
173 173 return '', '', p.returncode
174 174 out, err = out_err
175 175 return py3compat.bytes_to_str(out), py3compat.bytes_to_str(err), p.returncode
176 176
177 177 def arg_split(s, posix=False, strict=True):
178 178 """Split a command line's arguments in a shell-like manner.
179 179
180 180 This is a modified version of the standard library's shlex.split()
181 181 function, but with a default of posix=False for splitting, so that quotes
182 182 in inputs are respected.
183 183
184 184 if strict=False, then any errors shlex.split would raise will result in the
185 185 unparsed remainder being the last element of the list, rather than raising.
186 186 This is because we sometimes use arg_split to parse things other than
187 187 command-line args.
188 188 """
189 189
190 # Unfortunately, python's shlex module is buggy with unicode input:
191 # http://bugs.python.org/issue1170
192 # At least encoding the input when it's unicode seems to help, but there
193 # may be more problems lurking. Apparently this is fixed in python3.
194 is_unicode = False
195 if (not py3compat.PY3) and isinstance(s, unicode):
196 is_unicode = True
197 s = s.encode('utf-8')
198 190 lex = shlex.shlex(s, posix=posix)
199 191 lex.whitespace_split = True
200 192 # Extract tokens, ensuring that things like leaving open quotes
201 193 # does not cause this to raise. This is important, because we
202 194 # sometimes pass Python source through this (e.g. %timeit f(" ")),
203 195 # and it shouldn't raise an exception.
204 196 # It may be a bad idea to parse things that are not command-line args
205 197 # through this function, but we do, so let's be safe about it.
206 198 lex.commenters='' #fix for GH-1269
207 199 tokens = []
208 200 while True:
209 201 try:
210 202 tokens.append(next(lex))
211 203 except StopIteration:
212 204 break
213 205 except ValueError:
214 206 if strict:
215 207 raise
216 208 # couldn't parse, get remaining blob as last token
217 209 tokens.append(lex.token)
218 210 break
219
220 if is_unicode:
221 # Convert the tokens back to unicode.
222 tokens = [x.decode('utf-8') for x in tokens]
211
223 212 return tokens
General Comments 0
You need to be logged in to leave comments. Login now