Back to index

python3.2  3.2.2
Public Member Functions | Public Attributes | Static Public Attributes | Private Member Functions | Private Attributes
subprocess.Popen Class Reference
Inheritance diagram for subprocess.Popen:
Inheritance graph
[legend]
Collaboration diagram for subprocess.Popen:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def __init__
def __enter__
def __exit__
def __del__
def communicate
def poll
def wait
def send_signal
def terminate
def wait
def send_signal
def terminate
def kill

Public Attributes

 stdin
 stdout
 stderr
 pid
 returncode
 universal_newlines
_PyObject_HEAD_EXTRA Py_ssize_t ob_refcnt
struct _typeobjectob_type

Static Public Attributes

 kill = terminate

Private Member Functions

def _translate_newlines
def _get_handles
def _make_inheritable
def _find_w9xpopen
def _execute_child
def _internal_poll
def _readerthread
def _communicate
def _get_handles
def _close_fds
def _execute_child
def _handle_exitstatus
def _internal_poll
def _communicate
def _communicate_with_poll
def _communicate_with_select

Private Attributes

 _child_created
 _handle

Detailed Description

Definition at line 637 of file subprocess.py.


Constructor & Destructor Documentation

def subprocess.Popen.__init__ (   self,
  args,
  bufsize = 0,
  executable = None,
  stdin = None,
  stdout = None,
  stderr = None,
  preexec_fn = None,
  close_fds = _PLATFORM_DEFAULT_CLOSE_FDS,
  shell = False,
  cwd = None,
  env = None,
  universal_newlines = False,
  startupinfo = None,
  creationflags = 0,
  restore_signals = True,
  start_new_session = False,
  pass_fds = () 
)
Create new Popen instance.

Definition at line 644 of file subprocess.py.

00644 
00645                  pass_fds=()):
00646         """Create new Popen instance."""
00647         _cleanup()
00648 
00649         self._child_created = False
00650         if bufsize is None:
00651             bufsize = 0  # Restore default
00652         if not isinstance(bufsize, int):
00653             raise TypeError("bufsize must be an integer")
00654 
00655         if mswindows:
00656             if preexec_fn is not None:
00657                 raise ValueError("preexec_fn is not supported on Windows "
00658                                  "platforms")
00659             any_stdio_set = (stdin is not None or stdout is not None or
00660                              stderr is not None)
00661             if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
00662                 if any_stdio_set:
00663                     close_fds = False
00664                 else:
00665                     close_fds = True
00666             elif close_fds and any_stdio_set:
00667                 raise ValueError(
00668                         "close_fds is not supported on Windows platforms"
00669                         " if you redirect stdin/stdout/stderr")
00670         else:
00671             # POSIX
00672             if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
00673                 close_fds = True
00674             if pass_fds and not close_fds:
00675                 warnings.warn("pass_fds overriding close_fds.", RuntimeWarning)
00676                 close_fds = True
00677             if startupinfo is not None:
00678                 raise ValueError("startupinfo is only supported on Windows "
00679                                  "platforms")
00680             if creationflags != 0:
00681                 raise ValueError("creationflags is only supported on Windows "
00682                                  "platforms")
00683 
00684         self.stdin = None
00685         self.stdout = None
00686         self.stderr = None
00687         self.pid = None
00688         self.returncode = None
00689         self.universal_newlines = universal_newlines
00690 
00691         # Input and output objects. The general principle is like
00692         # this:
00693         #
00694         # Parent                   Child
00695         # ------                   -----
00696         # p2cwrite   ---stdin--->  p2cread
00697         # c2pread    <--stdout---  c2pwrite
00698         # errread    <--stderr---  errwrite
00699         #
00700         # On POSIX, the child objects are file descriptors.  On
00701         # Windows, these are Windows file handles.  The parent objects
00702         # are file descriptors on both platforms.  The parent objects
00703         # are -1 when not using PIPEs. The child objects are -1
00704         # when not redirecting.
00705 
00706         (p2cread, p2cwrite,
00707          c2pread, c2pwrite,
00708          errread, errwrite) = self._get_handles(stdin, stdout, stderr)
00709 
00710         # We wrap OS handles *before* launching the child, otherwise a
00711         # quickly terminating child could make our fds unwrappable
00712         # (see #8458).
00713 
00714         if mswindows:
00715             if p2cwrite != -1:
00716                 p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
00717             if c2pread != -1:
00718                 c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
00719             if errread != -1:
00720                 errread = msvcrt.open_osfhandle(errread.Detach(), 0)
00721 
00722         if p2cwrite != -1:
00723             self.stdin = io.open(p2cwrite, 'wb', bufsize)
00724             if self.universal_newlines:
00725                 self.stdin = io.TextIOWrapper(self.stdin, write_through=True)
00726         if c2pread != -1:
00727             self.stdout = io.open(c2pread, 'rb', bufsize)
00728             if universal_newlines:
00729                 self.stdout = io.TextIOWrapper(self.stdout)
00730         if errread != -1:
00731             self.stderr = io.open(errread, 'rb', bufsize)
00732             if universal_newlines:
00733                 self.stderr = io.TextIOWrapper(self.stderr)
00734 
00735         try:
00736             self._execute_child(args, executable, preexec_fn, close_fds,
00737                                 pass_fds, cwd, env, universal_newlines,
00738                                 startupinfo, creationflags, shell,
00739                                 p2cread, p2cwrite,
00740                                 c2pread, c2pwrite,
00741                                 errread, errwrite,
00742                                 restore_signals, start_new_session)
00743         except:
00744             # Cleanup if the child failed starting
00745             for f in filter(None, [self.stdin, self.stdout, self.stderr]):
00746                 try:
00747                     f.close()
00748                 except EnvironmentError:
00749                     # Ignore EBADF or other errors
00750                     pass
00751             raise
00752 

Here is the call graph for this function:

Here is the caller graph for this function:

def subprocess.Popen.__del__ (   self,
  _maxsize = sys.maxsize,
  _active = _active 
)

Definition at line 770 of file subprocess.py.

00770 
00771     def __del__(self, _maxsize=sys.maxsize, _active=_active):
00772         # If __init__ hasn't had a chance to execute (e.g. if it
00773         # was passed an undeclared keyword argument), we don't
00774         # have a _child_created attribute at all.
00775         if not getattr(self, '_child_created', False):
00776             # We didn't get to successfully create a child process.
00777             return
00778         # In case the child hasn't been waited on, check if it's done.
00779         self._internal_poll(_deadstate=_maxsize)
00780         if self.returncode is None and _active is not None:
00781             # Child is still running, keep us alive until we can wait on it.
00782             _active.append(self)
00783 

Here is the call graph for this function:


Member Function Documentation

Definition at line 757 of file subprocess.py.

00757 
00758     def __enter__(self):
00759         return self

def subprocess.Popen.__exit__ (   self,
  type,
  value,
  traceback 
)

Definition at line 760 of file subprocess.py.

00760 
00761     def __exit__(self, type, value, traceback):
00762         if self.stdout:
00763             self.stdout.close()
00764         if self.stderr:
00765             self.stderr.close()
00766         if self.stdin:
00767             self.stdin.close()
00768         # Wait for the process to terminate, to avoid zombies.
00769         self.wait()

Here is the call graph for this function:

Here is the caller graph for this function:

def subprocess.Popen._close_fds (   self,
  fds_to_keep 
) [private]

Definition at line 1127 of file subprocess.py.

01127 
01128         def _close_fds(self, fds_to_keep):
01129             start_fd = 3
01130             for fd in sorted(fds_to_keep):
01131                 if fd >= start_fd:
01132                     os.closerange(start_fd, fd)
01133                     start_fd = fd + 1
01134             if start_fd <= MAXFD:
01135                 os.closerange(start_fd, MAXFD)
01136 

Here is the call graph for this function:

Here is the caller graph for this function:

def subprocess.Popen._communicate (   self,
  input 
) [private]

Definition at line 1019 of file subprocess.py.

01019 
01020         def _communicate(self, input):
01021             stdout = None # Return
01022             stderr = None # Return
01023 
01024             if self.stdout:
01025                 stdout = []
01026                 stdout_thread = threading.Thread(target=self._readerthread,
01027                                                  args=(self.stdout, stdout))
01028                 stdout_thread.daemon = True
01029                 stdout_thread.start()
01030             if self.stderr:
01031                 stderr = []
01032                 stderr_thread = threading.Thread(target=self._readerthread,
01033                                                  args=(self.stderr, stderr))
01034                 stderr_thread.daemon = True
01035                 stderr_thread.start()
01036 
01037             if self.stdin:
01038                 if input is not None:
01039                     try:
01040                         self.stdin.write(input)
01041                     except IOError as e:
01042                         if e.errno != errno.EPIPE:
01043                             raise
01044                 self.stdin.close()
01045 
01046             if self.stdout:
01047                 stdout_thread.join()
01048             if self.stderr:
01049                 stderr_thread.join()
01050 
01051             # All data exchanged.  Translate lists into strings.
01052             if stdout is not None:
01053                 stdout = stdout[0]
01054             if stderr is not None:
01055                 stderr = stderr[0]
01056 
01057             self.wait()
01058             return (stdout, stderr)

Here is the call graph for this function:

Here is the caller graph for this function:

def subprocess.Popen._communicate (   self,
  input 
) [private]

Definition at line 1411 of file subprocess.py.

01411 
01412         def _communicate(self, input):
01413             if self.stdin:
01414                 # Flush stdio buffer.  This might block, if the user has
01415                 # been writing to .stdin in an uncontrolled fashion.
01416                 self.stdin.flush()
01417                 if not input:
01418                     self.stdin.close()
01419 
01420             if _has_poll:
01421                 stdout, stderr = self._communicate_with_poll(input)
01422             else:
01423                 stdout, stderr = self._communicate_with_select(input)
01424 
01425             # All data exchanged.  Translate lists into strings.
01426             if stdout is not None:
01427                 stdout = b''.join(stdout)
01428             if stderr is not None:
01429                 stderr = b''.join(stderr)
01430 
01431             # Translate newlines, if requested.
01432             # This also turns bytes into strings.
01433             if self.universal_newlines:
01434                 if stdout is not None:
01435                     stdout = self._translate_newlines(stdout,
01436                                                       self.stdout.encoding)
01437                 if stderr is not None:
01438                     stderr = self._translate_newlines(stderr,
01439                                                       self.stderr.encoding)
01440 
01441             self.wait()
01442             return (stdout, stderr)
01443 

Here is the call graph for this function:

def subprocess.Popen._communicate_with_poll (   self,
  input 
) [private]

Definition at line 1444 of file subprocess.py.

01444 
01445         def _communicate_with_poll(self, input):
01446             stdout = None # Return
01447             stderr = None # Return
01448             fd2file = {}
01449             fd2output = {}
01450 
01451             poller = select.poll()
01452             def register_and_append(file_obj, eventmask):
01453                 poller.register(file_obj.fileno(), eventmask)
01454                 fd2file[file_obj.fileno()] = file_obj
01455 
01456             def close_unregister_and_remove(fd):
01457                 poller.unregister(fd)
01458                 fd2file[fd].close()
01459                 fd2file.pop(fd)
01460 
01461             if self.stdin and input:
01462                 register_and_append(self.stdin, select.POLLOUT)
01463 
01464             select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI
01465             if self.stdout:
01466                 register_and_append(self.stdout, select_POLLIN_POLLPRI)
01467                 fd2output[self.stdout.fileno()] = stdout = []
01468             if self.stderr:
01469                 register_and_append(self.stderr, select_POLLIN_POLLPRI)
01470                 fd2output[self.stderr.fileno()] = stderr = []
01471 
01472             input_offset = 0
01473             while fd2file:
01474                 try:
01475                     ready = poller.poll()
01476                 except select.error as e:
01477                     if e.args[0] == errno.EINTR:
01478                         continue
01479                     raise
01480 
01481                 # XXX Rewrite these to use non-blocking I/O on the
01482                 # file objects; they are no longer using C stdio!
01483 
01484                 for fd, mode in ready:
01485                     if mode & select.POLLOUT:
01486                         chunk = input[input_offset : input_offset + _PIPE_BUF]
01487                         try:
01488                             input_offset += os.write(fd, chunk)
01489                         except OSError as e:
01490                             if e.errno == errno.EPIPE:
01491                                 close_unregister_and_remove(fd)
01492                             else:
01493                                 raise
01494                         else:
01495                             if input_offset >= len(input):
01496                                 close_unregister_and_remove(fd)
01497                     elif mode & select_POLLIN_POLLPRI:
01498                         data = os.read(fd, 4096)
01499                         if not data:
01500                             close_unregister_and_remove(fd)
01501                         fd2output[fd].append(data)
01502                     else:
01503                         # Ignore hang up or errors.
01504                         close_unregister_and_remove(fd)
01505 
01506             return (stdout, stderr)
01507 

Here is the call graph for this function:

Here is the caller graph for this function:

def subprocess.Popen._communicate_with_select (   self,
  input 
) [private]

Definition at line 1508 of file subprocess.py.

01508 
01509         def _communicate_with_select(self, input):
01510             read_set = []
01511             write_set = []
01512             stdout = None # Return
01513             stderr = None # Return
01514 
01515             if self.stdin and input:
01516                 write_set.append(self.stdin)
01517             if self.stdout:
01518                 read_set.append(self.stdout)
01519                 stdout = []
01520             if self.stderr:
01521                 read_set.append(self.stderr)
01522                 stderr = []
01523 
01524             input_offset = 0
01525             while read_set or write_set:
01526                 try:
01527                     rlist, wlist, xlist = select.select(read_set, write_set, [])
01528                 except select.error as e:
01529                     if e.args[0] == errno.EINTR:
01530                         continue
01531                     raise
01532 
01533                 # XXX Rewrite these to use non-blocking I/O on the
01534                 # file objects; they are no longer using C stdio!
01535 
01536                 if self.stdin in wlist:
01537                     chunk = input[input_offset : input_offset + _PIPE_BUF]
01538                     try:
01539                         bytes_written = os.write(self.stdin.fileno(), chunk)
01540                     except OSError as e:
01541                         if e.errno == errno.EPIPE:
01542                             self.stdin.close()
01543                             write_set.remove(self.stdin)
01544                         else:
01545                             raise
01546                     else:
01547                         input_offset += bytes_written
01548                         if input_offset >= len(input):
01549                             self.stdin.close()
01550                             write_set.remove(self.stdin)
01551 
01552                 if self.stdout in rlist:
01553                     data = os.read(self.stdout.fileno(), 1024)
01554                     if not data:
01555                         self.stdout.close()
01556                         read_set.remove(self.stdout)
01557                     stdout.append(data)
01558 
01559                 if self.stderr in rlist:
01560                     data = os.read(self.stderr.fileno(), 1024)
01561                     if not data:
01562                         self.stderr.close()
01563                         read_set.remove(self.stderr)
01564                     stderr.append(data)
01565 
01566             return (stdout, stderr)
01567 

Here is the caller graph for this function:

def subprocess.Popen._execute_child (   self,
  args,
  executable,
  preexec_fn,
  close_fds,
  pass_fds,
  cwd,
  env,
  universal_newlines,
  startupinfo,
  creationflags,
  shell,
  p2cread,
  p2cwrite,
  c2pread,
  c2pwrite,
  errread,
  errwrite,
  unused_restore_signals,
  unused_start_new_session 
) [private]
Execute program (MS Windows version)

Definition at line 913 of file subprocess.py.

00913 
00914                            unused_restore_signals, unused_start_new_session):
00915             """Execute program (MS Windows version)"""
00916 
00917             assert not pass_fds, "pass_fds not supported on Windows."
00918 
00919             if not isinstance(args, str):
00920                 args = list2cmdline(args)
00921 
00922             # Process startup details
00923             if startupinfo is None:
00924                 startupinfo = STARTUPINFO()
00925             if -1 not in (p2cread, c2pwrite, errwrite):
00926                 startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES
00927                 startupinfo.hStdInput = p2cread
00928                 startupinfo.hStdOutput = c2pwrite
00929                 startupinfo.hStdError = errwrite
00930 
00931             if shell:
00932                 startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
00933                 startupinfo.wShowWindow = _subprocess.SW_HIDE
00934                 comspec = os.environ.get("COMSPEC", "cmd.exe")
00935                 args = '{} /c "{}"'.format (comspec, args)
00936                 if (_subprocess.GetVersion() >= 0x80000000 or
00937                         os.path.basename(comspec).lower() == "command.com"):
00938                     # Win9x, or using command.com on NT. We need to
00939                     # use the w9xpopen intermediate program. For more
00940                     # information, see KB Q150956
00941                     # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
00942                     w9xpopen = self._find_w9xpopen()
00943                     args = '"%s" %s' % (w9xpopen, args)
00944                     # Not passing CREATE_NEW_CONSOLE has been known to
00945                     # cause random failures on win9x.  Specifically a
00946                     # dialog: "Your program accessed mem currently in
00947                     # use at xxx" and a hopeful warning about the
00948                     # stability of your system.  Cost is Ctrl+C won't
00949                     # kill children.
00950                     creationflags |= _subprocess.CREATE_NEW_CONSOLE
00951 
00952             # Start the process
00953             try:
00954                 hp, ht, pid, tid = _subprocess.CreateProcess(executable, args,
00955                                          # no special security
00956                                          None, None,
00957                                          int(not close_fds),
00958                                          creationflags,
00959                                          env,
00960                                          cwd,
00961                                          startupinfo)
00962             except pywintypes.error as e:
00963                 # Translate pywintypes.error to WindowsError, which is
00964                 # a subclass of OSError.  FIXME: We should really
00965                 # translate errno using _sys_errlist (or similar), but
00966                 # how can this be done from Python?
00967                 raise WindowsError(*e.args)
00968             finally:
00969                 # Child is launched. Close the parent's copy of those pipe
00970                 # handles that only the child should have open.  You need
00971                 # to make sure that no handles to the write end of the
00972                 # output pipe are maintained in this process or else the
00973                 # pipe will not close when the child process exits and the
00974                 # ReadFile will hang.
00975                 if p2cread != -1:
00976                     p2cread.Close()
00977                 if c2pwrite != -1:
00978                     c2pwrite.Close()
00979                 if errwrite != -1:
00980                     errwrite.Close()
00981 
00982             # Retain the process handle, but close the thread handle
00983             self._child_created = True
00984             self._handle = hp
00985             self.pid = pid
00986             ht.Close()

Here is the call graph for this function:

Here is the caller graph for this function:

def subprocess.Popen._execute_child (   self,
  args,
  executable,
  preexec_fn,
  close_fds,
  pass_fds,
  cwd,
  env,
  universal_newlines,
  startupinfo,
  creationflags,
  shell,
  p2cread,
  p2cwrite,
  c2pread,
  c2pwrite,
  errread,
  errwrite,
  restore_signals,
  start_new_session 
) [private]
Execute program (POSIX version)

Definition at line 1143 of file subprocess.py.

01143 
01144                            restore_signals, start_new_session):
01145             """Execute program (POSIX version)"""
01146 
01147             if isinstance(args, str):
01148                 args = [args]
01149             else:
01150                 args = list(args)
01151 
01152             if shell:
01153                 args = ["/bin/sh", "-c"] + args
01154                 if executable:
01155                     args[0] = executable
01156 
01157             if executable is None:
01158                 executable = args[0]
01159 
01160             # For transferring possible exec failure from child to parent.
01161             # Data format: "exception name:hex errno:description"
01162             # Pickle is not used; it is complex and involves memory allocation.
01163             errpipe_read, errpipe_write = _create_pipe()
01164             try:
01165                 try:
01166 
01167                     if _posixsubprocess:
01168                         # We must avoid complex work that could involve
01169                         # malloc or free in the child process to avoid
01170                         # potential deadlocks, thus we do all this here.
01171                         # and pass it to fork_exec()
01172 
01173                         if env is not None:
01174                             env_list = [os.fsencode(k) + b'=' + os.fsencode(v)
01175                                         for k, v in env.items()]
01176                         else:
01177                             env_list = None  # Use execv instead of execve.
01178                         executable = os.fsencode(executable)
01179                         if os.path.dirname(executable):
01180                             executable_list = (executable,)
01181                         else:
01182                             # This matches the behavior of os._execvpe().
01183                             executable_list = tuple(
01184                                 os.path.join(os.fsencode(dir), executable)
01185                                 for dir in os.get_exec_path(env))
01186                         fds_to_keep = set(pass_fds)
01187                         fds_to_keep.add(errpipe_write)
01188                         self.pid = _posixsubprocess.fork_exec(
01189                                 args, executable_list,
01190                                 close_fds, sorted(fds_to_keep), cwd, env_list,
01191                                 p2cread, p2cwrite, c2pread, c2pwrite,
01192                                 errread, errwrite,
01193                                 errpipe_read, errpipe_write,
01194                                 restore_signals, start_new_session, preexec_fn)
01195                     else:
01196                         # Pure Python implementation: It is not thread safe.
01197                         # This implementation may deadlock in the child if your
01198                         # parent process has any other threads running.
01199 
01200                         gc_was_enabled = gc.isenabled()
01201                         # Disable gc to avoid bug where gc -> file_dealloc ->
01202                         # write to stderr -> hang.  See issue1336
01203                         gc.disable()
01204                         try:
01205                             self.pid = os.fork()
01206                         except:
01207                             if gc_was_enabled:
01208                                 gc.enable()
01209                             raise
01210                         self._child_created = True
01211                         if self.pid == 0:
01212                             # Child
01213                             try:
01214                                 # Close parent's pipe ends
01215                                 if p2cwrite != -1:
01216                                     os.close(p2cwrite)
01217                                 if c2pread != -1:
01218                                     os.close(c2pread)
01219                                 if errread != -1:
01220                                     os.close(errread)
01221                                 os.close(errpipe_read)
01222 
01223                                 # When duping fds, if there arises a situation
01224                                 # where one of the fds is either 0, 1 or 2, it
01225                                 # is possible that it is overwritten (#12607).
01226                                 if c2pwrite == 0:
01227                                     c2pwrite = os.dup(c2pwrite)
01228                                 if errwrite == 0 or errwrite == 1:
01229                                     errwrite = os.dup(errwrite)
01230 
01231                                 # Dup fds for child
01232                                 def _dup2(a, b):
01233                                     # dup2() removes the CLOEXEC flag but
01234                                     # we must do it ourselves if dup2()
01235                                     # would be a no-op (issue #10806).
01236                                     if a == b:
01237                                         _set_cloexec(a, False)
01238                                     elif a != -1:
01239                                         os.dup2(a, b)
01240                                 _dup2(p2cread, 0)
01241                                 _dup2(c2pwrite, 1)
01242                                 _dup2(errwrite, 2)
01243 
01244                                 # Close pipe fds.  Make sure we don't close the
01245                                 # same fd more than once, or standard fds.
01246                                 closed = set()
01247                                 for fd in [p2cread, c2pwrite, errwrite]:
01248                                     if fd > 2 and fd not in closed:
01249                                         os.close(fd)
01250                                         closed.add(fd)
01251 
01252                                 # Close all other fds, if asked for
01253                                 if close_fds:
01254                                     fds_to_keep = set(pass_fds)
01255                                     fds_to_keep.add(errpipe_write)
01256                                     self._close_fds(fds_to_keep)
01257 
01258 
01259                                 if cwd is not None:
01260                                     os.chdir(cwd)
01261 
01262                                 # This is a copy of Python/pythonrun.c
01263                                 # _Py_RestoreSignals().  If that were exposed
01264                                 # as a sys._py_restoresignals func it would be
01265                                 # better.. but this pure python implementation
01266                                 # isn't likely to be used much anymore.
01267                                 if restore_signals:
01268                                     signals = ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ')
01269                                     for sig in signals:
01270                                         if hasattr(signal, sig):
01271                                             signal.signal(getattr(signal, sig),
01272                                                           signal.SIG_DFL)
01273 
01274                                 if start_new_session and hasattr(os, 'setsid'):
01275                                     os.setsid()
01276 
01277                                 if preexec_fn:
01278                                     preexec_fn()
01279 
01280                                 if env is None:
01281                                     os.execvp(executable, args)
01282                                 else:
01283                                     os.execvpe(executable, args, env)
01284 
01285                             except:
01286                                 try:
01287                                     exc_type, exc_value = sys.exc_info()[:2]
01288                                     if isinstance(exc_value, OSError):
01289                                         errno_num = exc_value.errno
01290                                     else:
01291                                         errno_num = 0
01292                                     message = '%s:%x:%s' % (exc_type.__name__,
01293                                                             errno_num, exc_value)
01294                                     message = message.encode(errors="surrogatepass")
01295                                     os.write(errpipe_write, message)
01296                                 except Exception:
01297                                     # We MUST not allow anything odd happening
01298                                     # above to prevent us from exiting below.
01299                                     pass
01300 
01301                             # This exitcode won't be reported to applications
01302                             # so it really doesn't matter what we return.
01303                             os._exit(255)
01304 
01305                         # Parent
01306                         if gc_was_enabled:
01307                             gc.enable()
01308                 finally:
01309                     # be sure the FD is closed no matter what
01310                     os.close(errpipe_write)
01311 
01312                 if p2cread != -1 and p2cwrite != -1:
01313                     os.close(p2cread)
01314                 if c2pwrite != -1 and c2pread != -1:
01315                     os.close(c2pwrite)
01316                 if errwrite != -1 and errread != -1:
01317                     os.close(errwrite)
01318 
01319                 # Wait for exec to fail or succeed; possibly raising an
01320                 # exception (limited in size)
01321                 data = bytearray()
01322                 while True:
01323                     part = _eintr_retry_call(os.read, errpipe_read, 50000)
01324                     data += part
01325                     if not part or len(data) > 50000:
01326                         break
01327             finally:
01328                 # be sure the FD is closed no matter what
01329                 os.close(errpipe_read)
01330 
01331             if data:
01332                 try:
01333                     _eintr_retry_call(os.waitpid, self.pid, 0)
01334                 except OSError as e:
01335                     if e.errno != errno.ECHILD:
01336                         raise
01337                 try:
01338                     exception_name, hex_errno, err_msg = data.split(b':', 2)
01339                 except ValueError:
01340                     print('Bad exception data:', repr(data))
01341                     exception_name = b'RuntimeError'
01342                     hex_errno = b'0'
01343                     err_msg = b'Unknown'
01344                 child_exception_type = getattr(
01345                         builtins, exception_name.decode('ascii'),
01346                         RuntimeError)
01347                 for fd in (p2cwrite, c2pread, errread):
01348                     if fd != -1:
01349                         os.close(fd)
01350                 err_msg = err_msg.decode(errors="surrogatepass")
01351                 if issubclass(child_exception_type, OSError) and hex_errno:
01352                     errno_num = int(hex_errno, 16)
01353                     if errno_num != 0:
01354                         err_msg = os.strerror(errno_num)
01355                         if errno_num == errno.ENOENT:
01356                             err_msg += ': ' + repr(args[0])
01357                     raise child_exception_type(errno_num, err_msg)
01358                 raise child_exception_type(err_msg)
01359 

Here is the call graph for this function:

def subprocess.Popen._find_w9xpopen (   self) [private]
Find and return absolut path to w9xpopen.exe

Definition at line 890 of file subprocess.py.

00890 
00891         def _find_w9xpopen(self):
00892             """Find and return absolut path to w9xpopen.exe"""
00893             w9xpopen = os.path.join(
00894                             os.path.dirname(_subprocess.GetModuleFileName(0)),
00895                                     "w9xpopen.exe")
00896             if not os.path.exists(w9xpopen):
00897                 # Eeek - file-not-found - possibly an embedding
00898                 # situation - see if we can locate it in sys.exec_prefix
00899                 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
00900                                         "w9xpopen.exe")
00901                 if not os.path.exists(w9xpopen):
00902                     raise RuntimeError("Cannot locate w9xpopen.exe, which is "
00903                                        "needed for Popen to work with your "
00904                                        "shell or platform.")
00905             return w9xpopen
00906 

Here is the call graph for this function:

Here is the caller graph for this function:

def subprocess.Popen._get_handles (   self,
  stdin,
  stdout,
  stderr 
) [private]
Construct and return tuple with IO objects:
p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite

Definition at line 826 of file subprocess.py.

00826 
00827         def _get_handles(self, stdin, stdout, stderr):
00828             """Construct and return tuple with IO objects:
00829             p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
00830             """
00831             if stdin is None and stdout is None and stderr is None:
00832                 return (-1, -1, -1, -1, -1, -1)
00833 
00834             p2cread, p2cwrite = -1, -1
00835             c2pread, c2pwrite = -1, -1
00836             errread, errwrite = -1, -1
00837 
00838             if stdin is None:
00839                 p2cread = _subprocess.GetStdHandle(_subprocess.STD_INPUT_HANDLE)
00840                 if p2cread is None:
00841                     p2cread, _ = _subprocess.CreatePipe(None, 0)
00842             elif stdin == PIPE:
00843                 p2cread, p2cwrite = _subprocess.CreatePipe(None, 0)
00844             elif isinstance(stdin, int):
00845                 p2cread = msvcrt.get_osfhandle(stdin)
00846             else:
00847                 # Assuming file-like object
00848                 p2cread = msvcrt.get_osfhandle(stdin.fileno())
00849             p2cread = self._make_inheritable(p2cread)
00850 
00851             if stdout is None:
00852                 c2pwrite = _subprocess.GetStdHandle(_subprocess.STD_OUTPUT_HANDLE)
00853                 if c2pwrite is None:
00854                     _, c2pwrite = _subprocess.CreatePipe(None, 0)
00855             elif stdout == PIPE:
00856                 c2pread, c2pwrite = _subprocess.CreatePipe(None, 0)
00857             elif isinstance(stdout, int):
00858                 c2pwrite = msvcrt.get_osfhandle(stdout)
00859             else:
00860                 # Assuming file-like object
00861                 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
00862             c2pwrite = self._make_inheritable(c2pwrite)
00863 
00864             if stderr is None:
00865                 errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE)
00866                 if errwrite is None:
00867                     _, errwrite = _subprocess.CreatePipe(None, 0)
00868             elif stderr == PIPE:
00869                 errread, errwrite = _subprocess.CreatePipe(None, 0)
00870             elif stderr == STDOUT:
00871                 errwrite = c2pwrite
00872             elif isinstance(stderr, int):
00873                 errwrite = msvcrt.get_osfhandle(stderr)
00874             else:
00875                 # Assuming file-like object
00876                 errwrite = msvcrt.get_osfhandle(stderr.fileno())
00877             errwrite = self._make_inheritable(errwrite)
00878 
00879             return (p2cread, p2cwrite,
00880                     c2pread, c2pwrite,
00881                     errread, errwrite)
00882 

Here is the call graph for this function:

Here is the caller graph for this function:

def subprocess.Popen._get_handles (   self,
  stdin,
  stdout,
  stderr 
) [private]
Construct and return tuple with IO objects:
p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite

Definition at line 1082 of file subprocess.py.

01082 
01083         def _get_handles(self, stdin, stdout, stderr):
01084             """Construct and return tuple with IO objects:
01085             p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
01086             """
01087             p2cread, p2cwrite = -1, -1
01088             c2pread, c2pwrite = -1, -1
01089             errread, errwrite = -1, -1
01090 
01091             if stdin is None:
01092                 pass
01093             elif stdin == PIPE:
01094                 p2cread, p2cwrite = _create_pipe()
01095             elif isinstance(stdin, int):
01096                 p2cread = stdin
01097             else:
01098                 # Assuming file-like object
01099                 p2cread = stdin.fileno()
01100 
01101             if stdout is None:
01102                 pass
01103             elif stdout == PIPE:
01104                 c2pread, c2pwrite = _create_pipe()
01105             elif isinstance(stdout, int):
01106                 c2pwrite = stdout
01107             else:
01108                 # Assuming file-like object
01109                 c2pwrite = stdout.fileno()
01110 
01111             if stderr is None:
01112                 pass
01113             elif stderr == PIPE:
01114                 errread, errwrite = _create_pipe()
01115             elif stderr == STDOUT:
01116                 errwrite = c2pwrite
01117             elif isinstance(stderr, int):
01118                 errwrite = stderr
01119             else:
01120                 # Assuming file-like object
01121                 errwrite = stderr.fileno()
01122 
01123             return (p2cread, p2cwrite,
01124                     c2pread, c2pwrite,
01125                     errread, errwrite)
01126 

Here is the call graph for this function:

def subprocess.Popen._handle_exitstatus (   self,
  sts,
  _WIFSIGNALED = os.WIFSIGNALED,
  _WTERMSIG = os.WTERMSIG,
  _WIFEXITED = os.WIFEXITED,
  _WEXITSTATUS = os.WEXITSTATUS 
) [private]

Definition at line 1362 of file subprocess.py.

01362 
01363                 _WEXITSTATUS=os.WEXITSTATUS):
01364             # This method is called (indirectly) by __del__, so it cannot
01365             # refer to anything outside of its local scope."""
01366             if _WIFSIGNALED(sts):
01367                 self.returncode = -_WTERMSIG(sts)
01368             elif _WIFEXITED(sts):
01369                 self.returncode = _WEXITSTATUS(sts)
01370             else:
01371                 # Should never happen
01372                 raise RuntimeError("Unknown child exit status!")
01373 

Here is the call graph for this function:

Here is the caller graph for this function:

def subprocess.Popen._internal_poll (   self,
  _deadstate = None,
  _WaitForSingleObject = _subprocess.WaitForSingleObject,
  _WAIT_OBJECT_0 = _subprocess.WAIT_OBJECT_0,
  _GetExitCodeProcess = _subprocess.GetExitCodeProcess 
) [private]
Check if child process has terminated.  Returns returncode
attribute.

This method is called by __del__, so it can only refer to objects
in its local scope.

Definition at line 990 of file subprocess.py.

00990 
00991                 _GetExitCodeProcess=_subprocess.GetExitCodeProcess):
00992             """Check if child process has terminated.  Returns returncode
00993             attribute.
00994 
00995             This method is called by __del__, so it can only refer to objects
00996             in its local scope.
00997 
00998             """
00999             if self.returncode is None:
01000                 if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
01001                     self.returncode = _GetExitCodeProcess(self._handle)
01002             return self.returncode
01003 

Here is the caller graph for this function:

def subprocess.Popen._internal_poll (   self,
  _deadstate = None,
  _waitpid = os.waitpid,
  _WNOHANG = os.WNOHANG,
  _os_error = os.error 
) [private]
Check if child process has terminated.  Returns returncode
attribute.

This method is called by __del__, so it cannot reference anything
outside of the local scope (nor can any methods it calls).

Definition at line 1375 of file subprocess.py.

01375 
01376                 _WNOHANG=os.WNOHANG, _os_error=os.error):
01377             """Check if child process has terminated.  Returns returncode
01378             attribute.
01379 
01380             This method is called by __del__, so it cannot reference anything
01381             outside of the local scope (nor can any methods it calls).
01382 
01383             """
01384             if self.returncode is None:
01385                 try:
01386                     pid, sts = _waitpid(self.pid, _WNOHANG)
01387                     if pid == self.pid:
01388                         self._handle_exitstatus(sts)
01389                 except _os_error:
01390                     if _deadstate is not None:
01391                         self.returncode = _deadstate
01392             return self.returncode
01393 

Here is the call graph for this function:

def subprocess.Popen._make_inheritable (   self,
  handle 
) [private]
Return a duplicate of handle, which is inheritable

Definition at line 883 of file subprocess.py.

00883 
00884         def _make_inheritable(self, handle):
00885             """Return a duplicate of handle, which is inheritable"""
00886             return _subprocess.DuplicateHandle(_subprocess.GetCurrentProcess(),
00887                                 handle, _subprocess.GetCurrentProcess(), 0, 1,
00888                                 _subprocess.DUPLICATE_SAME_ACCESS)
00889 

Here is the caller graph for this function:

def subprocess.Popen._readerthread (   self,
  fh,
  buffer 
) [private]

Definition at line 1014 of file subprocess.py.

01014 
01015         def _readerthread(self, fh, buffer):
01016             buffer.append(fh.read())
01017             fh.close()
01018 

Here is the caller graph for this function:

def subprocess.Popen._translate_newlines (   self,
  data,
  encoding 
) [private]

Definition at line 753 of file subprocess.py.

00753 
00754     def _translate_newlines(self, data, encoding):
00755         data = data.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
00756         return data.decode(encoding)

Here is the call graph for this function:

Here is the caller graph for this function:

def subprocess.Popen.communicate (   self,
  input = None 
)
Interact with process: Send data to stdin.  Read data from
stdout and stderr, until end-of-file is reached.  Wait for
process to terminate.  The optional input argument should be a
string to be sent to the child process, or None, if no data
should be sent to the child.

communicate() returns a tuple (stdout, stderr).

Definition at line 784 of file subprocess.py.

00784 
00785     def communicate(self, input=None):
00786         """Interact with process: Send data to stdin.  Read data from
00787         stdout and stderr, until end-of-file is reached.  Wait for
00788         process to terminate.  The optional input argument should be a
00789         string to be sent to the child process, or None, if no data
00790         should be sent to the child.
00791 
00792         communicate() returns a tuple (stdout, stderr)."""
00793 
00794         # Optimization: If we are only using one pipe, or no pipe at
00795         # all, using select() or threads is unnecessary.
00796         if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
00797             stdout = None
00798             stderr = None
00799             if self.stdin:
00800                 if input:
00801                     try:
00802                         self.stdin.write(input)
00803                     except IOError as e:
00804                         if e.errno != errno.EPIPE and e.errno != errno.EINVAL:
00805                             raise
00806                 self.stdin.close()
00807             elif self.stdout:
00808                 stdout = _eintr_retry_call(self.stdout.read)
00809                 self.stdout.close()
00810             elif self.stderr:
00811                 stderr = _eintr_retry_call(self.stderr.read)
00812                 self.stderr.close()
00813             self.wait()
00814             return (stdout, stderr)
00815 
00816         return self._communicate(input)
00817 

Here is the call graph for this function:

def subprocess.Popen.kill (   self)
Kill the process with SIGKILL

Definition at line 1578 of file subprocess.py.

01578 
01579         def kill(self):
01580             """Kill the process with SIGKILL
01581             """
01582             self.send_signal(signal.SIGKILL)
01583 

Here is the call graph for this function:

def subprocess.Popen.poll (   self)

Definition at line 818 of file subprocess.py.

00818 
00819     def poll(self):
00820         return self._internal_poll()
00821 

Here is the call graph for this function:

def subprocess.Popen.send_signal (   self,
  sig 
)
Send a signal to the process

Definition at line 1059 of file subprocess.py.

01059 
01060         def send_signal(self, sig):
01061             """Send a signal to the process
01062             """
01063             if sig == signal.SIGTERM:
01064                 self.terminate()
01065             elif sig == signal.CTRL_C_EVENT:
01066                 os.kill(self.pid, signal.CTRL_C_EVENT)
01067             elif sig == signal.CTRL_BREAK_EVENT:
01068                 os.kill(self.pid, signal.CTRL_BREAK_EVENT)
01069             else:
01070                 raise ValueError("Unsupported signal: {}".format(sig))

Here is the call graph for this function:

Here is the caller graph for this function:

def subprocess.Popen.send_signal (   self,
  sig 
)
Send a signal to the process

Definition at line 1568 of file subprocess.py.

01568 
01569         def send_signal(self, sig):
01570             """Send a signal to the process
01571             """
01572             os.kill(self.pid, sig)

Here is the call graph for this function:

Terminates the process

Definition at line 1071 of file subprocess.py.

01071 
01072         def terminate(self):
01073             """Terminates the process
01074             """
01075             _subprocess.TerminateProcess(self._handle, 1)

Here is the caller graph for this function:

Terminate the process with SIGTERM

Definition at line 1573 of file subprocess.py.

01573 
01574         def terminate(self):
01575             """Terminate the process with SIGTERM
01576             """
01577             self.send_signal(signal.SIGTERM)

Here is the call graph for this function:

def subprocess.Popen.wait (   self)
Wait for child process to terminate.  Returns returncode
attribute.

Definition at line 1004 of file subprocess.py.

01004 
01005         def wait(self):
01006             """Wait for child process to terminate.  Returns returncode
01007             attribute."""
01008             if self.returncode is None:
01009                 _subprocess.WaitForSingleObject(self._handle,
01010                                                 _subprocess.INFINITE)
01011                 self.returncode = _subprocess.GetExitCodeProcess(self._handle)
01012             return self.returncode
01013 

Here is the caller graph for this function:

def subprocess.Popen.wait (   self)
Wait for child process to terminate.  Returns returncode
attribute.

Definition at line 1394 of file subprocess.py.

01394 
01395         def wait(self):
01396             """Wait for child process to terminate.  Returns returncode
01397             attribute."""
01398             if self.returncode is None:
01399                 try:
01400                     pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
01401                 except OSError as e:
01402                     if e.errno != errno.ECHILD:
01403                         raise
01404                     # This happens if SIGCLD is set to be ignored or waiting
01405                     # for child processes has otherwise been disabled for our
01406                     # process.  This child is dead, we can't get the status.
01407                     sts = 0
01408                 self._handle_exitstatus(sts)
01409             return self.returncode
01410 

Here is the call graph for this function:

Here is the caller graph for this function:


Member Data Documentation

Definition at line 648 of file subprocess.py.

Definition at line 983 of file subprocess.py.

Definition at line 1076 of file subprocess.py.

Definition at line 107 of file object.h.

struct _typeobject* _object::ob_type [inherited]

Definition at line 108 of file object.h.

Definition at line 686 of file subprocess.py.

Definition at line 687 of file subprocess.py.

Definition at line 685 of file subprocess.py.

Definition at line 683 of file subprocess.py.

Definition at line 684 of file subprocess.py.

Definition at line 688 of file subprocess.py.


The documentation for this class was generated from the following file: