Back to index

python3.2  3.2.2
Classes | Functions | Variables
subprocess Namespace Reference

Classes

class  CalledProcessError
class  STARTUPINFO
class  pywintypes
class  Popen

Functions

def _set_cloexec
def _create_pipe
def _cleanup
def _eintr_retry_call
def call
def check_call
def check_output
def list2cmdline
def getstatusoutput
def getoutput
def _demo_posix
def _demo_windows

Variables

tuple mswindows = (sys.platform == "win32")
tuple _has_poll = hasattr(select, 'poll')
 _posixsubprocess = None
tuple _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
tuple _FD_CLOEXEC = getattr(fcntl, 'FD_CLOEXEC', 1)
 _create_pipe = _posixsubprocess.cloexec_pipe
list __all__
tuple MAXFD = os.sysconf("SC_OPEN_MAX")
list _active = []
int PIPE = 1
int STDOUT = 2
tuple _PLATFORM_DEFAULT_CLOSE_FDS = object()

Function Documentation

def subprocess._cleanup ( ) [private]

Definition at line 434 of file subprocess.py.

00434 
00435 def _cleanup():
00436     for inst in _active[:]:
00437         res = inst._internal_poll(_deadstate=sys.maxsize)
00438         if res is not None and res >= 0:
00439             try:
00440                 _active.remove(inst)
00441             except ValueError:
00442                 # This can happen if two threads create a new Popen instance.
00443                 # It's harmless that it was already removed, so ignore.
00444                 pass

Here is the caller graph for this function:

def subprocess._create_pipe ( ) [private]

Definition at line 408 of file subprocess.py.

00408 
00409         def _create_pipe():
00410             fds = os.pipe()
00411             _set_cloexec(fds[0], True)
00412             _set_cloexec(fds[1], True)
00413             return fds

Here is the call graph for this function:

def subprocess._demo_posix ( ) [private]

Definition at line 1584 of file subprocess.py.

01584 
01585 def _demo_posix():
01586     #
01587     # Example 1: Simple redirection: Get process list
01588     #
01589     plist = Popen(["ps"], stdout=PIPE).communicate()[0]
01590     print("Process list:")
01591     print(plist)
01592 
01593     #
01594     # Example 2: Change uid before executing child
01595     #
01596     if os.getuid() == 0:
01597         p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
01598         p.wait()
01599 
01600     #
01601     # Example 3: Connecting several subprocesses
01602     #
01603     print("Looking for 'hda'...")
01604     p1 = Popen(["dmesg"], stdout=PIPE)
01605     p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
01606     print(repr(p2.communicate()[0]))
01607 
01608     #
01609     # Example 4: Catch execution error
01610     #
01611     print()
01612     print("Trying a weird file...")
01613     try:
01614         print(Popen(["/this/path/does/not/exist"]).communicate())
01615     except OSError as e:
01616         if e.errno == errno.ENOENT:
01617             print("The file didn't exist.  I thought so...")
01618             print("Child traceback:")
01619             print(e.child_traceback)
01620         else:
01621             print("Error", e.errno)
01622     else:
01623         print("Gosh.  No error.", file=sys.stderr)
01624 

Here is the caller graph for this function:

def subprocess._demo_windows ( ) [private]

Definition at line 1625 of file subprocess.py.

01625 
01626 def _demo_windows():
01627     #
01628     # Example 1: Connecting several subprocesses
01629     #
01630     print("Looking for 'PROMPT' in set output...")
01631     p1 = Popen("set", stdout=PIPE, shell=True)
01632     p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
01633     print(repr(p2.communicate()[0]))
01634 
01635     #
01636     # Example 2: Simple execution of program
01637     #
01638     print("Executing calc...")
01639     p = Popen("calc")
01640     p.wait()
01641 

Here is the call graph for this function:

def subprocess._eintr_retry_call (   func,
  args 
) [private]

Definition at line 449 of file subprocess.py.

00449 
00450 def _eintr_retry_call(func, *args):
00451     while True:
00452         try:
00453             return func(*args)
00454         except (OSError, IOError) as e:
00455             if e.errno == errno.EINTR:
00456                 continue
00457             raise
00458 

Here is the caller graph for this function:

def subprocess._set_cloexec (   fd,
  cloexec 
) [private]

Definition at line 398 of file subprocess.py.

00398 
00399     def _set_cloexec(fd, cloexec):
00400         old = fcntl.fcntl(fd, fcntl.F_GETFD)
00401         if cloexec:
00402             fcntl.fcntl(fd, fcntl.F_SETFD, old | _FD_CLOEXEC)
00403         else:
00404             fcntl.fcntl(fd, fcntl.F_SETFD, old & ~_FD_CLOEXEC)

Here is the caller graph for this function:

def subprocess.call (   popenargs,
  kwargs 
)
Run command with arguments.  Wait for command to complete, then
return the returncode attribute.

The arguments are the same as for the Popen constructor.  Example:

retcode = call(["ls", "-l"])

Definition at line 459 of file subprocess.py.

00459 
00460 def call(*popenargs, **kwargs):
00461     """Run command with arguments.  Wait for command to complete, then
00462     return the returncode attribute.
00463 
00464     The arguments are the same as for the Popen constructor.  Example:
00465 
00466     retcode = call(["ls", "-l"])
00467     """
00468     return Popen(*popenargs, **kwargs).wait()
00469 

Here is the call graph for this function:

Here is the caller graph for this function:

def subprocess.check_call (   popenargs,
  kwargs 
)
Run command with arguments.  Wait for command to complete.  If
the exit code was zero then return, otherwise raise
CalledProcessError.  The CalledProcessError object will have the
return code in the returncode attribute.

The arguments are the same as for the Popen constructor.  Example:

check_call(["ls", "-l"])

Definition at line 470 of file subprocess.py.

00470 
00471 def check_call(*popenargs, **kwargs):
00472     """Run command with arguments.  Wait for command to complete.  If
00473     the exit code was zero then return, otherwise raise
00474     CalledProcessError.  The CalledProcessError object will have the
00475     return code in the returncode attribute.
00476 
00477     The arguments are the same as for the Popen constructor.  Example:
00478 
00479     check_call(["ls", "-l"])
00480     """
00481     retcode = call(*popenargs, **kwargs)
00482     if retcode:
00483         cmd = kwargs.get("args")
00484         if cmd is None:
00485             cmd = popenargs[0]
00486         raise CalledProcessError(retcode, cmd)
00487     return 0
00488 

Here is the call graph for this function:

Here is the caller graph for this function:

def subprocess.check_output (   popenargs,
  kwargs 
)

Definition at line 489 of file subprocess.py.

00489 
00490 def check_output(*popenargs, **kwargs):
00491     r"""Run command with arguments and return its output as a byte string.
00492 
00493     If the exit code was non-zero it raises a CalledProcessError.  The
00494     CalledProcessError object will have the return code in the returncode
00495     attribute and output in the output attribute.
00496 
00497     The arguments are the same as for the Popen constructor.  Example:
00498 
00499     >>> check_output(["ls", "-l", "/dev/null"])
00500     b'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'
00501 
00502     The stdout argument is not allowed as it is used internally.
00503     To capture standard error in the result, use stderr=STDOUT.
00504 
00505     >>> check_output(["/bin/sh", "-c",
00506     ...               "ls -l non_existent_file ; exit 0"],
00507     ...              stderr=STDOUT)
00508     b'ls: non_existent_file: No such file or directory\n'
00509     """
00510     if 'stdout' in kwargs:
00511         raise ValueError('stdout argument not allowed, it will be overridden.')
00512     process = Popen(*popenargs, stdout=PIPE, **kwargs)
00513     output, unused_err = process.communicate()
00514     retcode = process.poll()
00515     if retcode:
00516         cmd = kwargs.get("args")
00517         if cmd is None:
00518             cmd = popenargs[0]
00519         raise CalledProcessError(retcode, cmd, output=output)
00520     return output
00521 

Here is the caller graph for this function:

def subprocess.getoutput (   cmd)
Return output (stdout or stderr) of executing cmd in a shell.

Like getstatusoutput(), except the exit status is ignored and the return
value is a string containing the command's output.  Example:

>>> import subprocess
>>> subprocess.getoutput('ls /bin/ls')
'/bin/ls'

Definition at line 621 of file subprocess.py.

00621 
00622 def getoutput(cmd):
00623     """Return output (stdout or stderr) of executing cmd in a shell.
00624 
00625     Like getstatusoutput(), except the exit status is ignored and the return
00626     value is a string containing the command's output.  Example:
00627 
00628     >>> import subprocess
00629     >>> subprocess.getoutput('ls /bin/ls')
00630     '/bin/ls'
00631     """
00632     return getstatusoutput(cmd)[1]
00633 

Here is the call graph for this function:

Here is the caller graph for this function:

Return (status, output) of executing cmd in a shell.

Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
(status, output).  cmd is actually run as '{ cmd ; } 2>&1', so that the
returned output will contain output or error messages.  A trailing newline
is stripped from the output.  The exit status for the command can be
interpreted according to the rules for the C function wait().  Example:

>>> import subprocess
>>> subprocess.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> subprocess.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> subprocess.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')

Definition at line 596 of file subprocess.py.

00596 
00597 def getstatusoutput(cmd):
00598     """Return (status, output) of executing cmd in a shell.
00599 
00600     Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
00601     (status, output).  cmd is actually run as '{ cmd ; } 2>&1', so that the
00602     returned output will contain output or error messages.  A trailing newline
00603     is stripped from the output.  The exit status for the command can be
00604     interpreted according to the rules for the C function wait().  Example:
00605 
00606     >>> import subprocess
00607     >>> subprocess.getstatusoutput('ls /bin/ls')
00608     (0, '/bin/ls')
00609     >>> subprocess.getstatusoutput('cat /bin/junk')
00610     (256, 'cat: /bin/junk: No such file or directory')
00611     >>> subprocess.getstatusoutput('/bin/junk')
00612     (256, 'sh: /bin/junk: not found')
00613     """
00614     pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
00615     text = pipe.read()
00616     sts = pipe.close()
00617     if sts is None: sts = 0
00618     if text[-1:] == '\n': text = text[:-1]
00619     return sts, text
00620 

Here is the call graph for this function:

Here is the caller graph for this function:

def subprocess.list2cmdline (   seq)
Translate a sequence of arguments into a command line
string, using the same rules as the MS C runtime:

1) Arguments are delimited by white space, which is either a
   space or a tab.

2) A string surrounded by double quotation marks is
   interpreted as a single argument, regardless of white space
   contained within.  A quoted string can be embedded in an
   argument.

3) A double quotation mark preceded by a backslash is
   interpreted as a literal double quotation mark.

4) Backslashes are interpreted literally, unless they
   immediately precede a double quotation mark.

5) If backslashes immediately precede a double quotation mark,
   every pair of backslashes is interpreted as a literal
   backslash.  If the number of backslashes is odd, the last
   backslash escapes the next double quotation mark as
   described in rule 3.

Definition at line 522 of file subprocess.py.

00522 
00523 def list2cmdline(seq):
00524     """
00525     Translate a sequence of arguments into a command line
00526     string, using the same rules as the MS C runtime:
00527 
00528     1) Arguments are delimited by white space, which is either a
00529        space or a tab.
00530 
00531     2) A string surrounded by double quotation marks is
00532        interpreted as a single argument, regardless of white space
00533        contained within.  A quoted string can be embedded in an
00534        argument.
00535 
00536     3) A double quotation mark preceded by a backslash is
00537        interpreted as a literal double quotation mark.
00538 
00539     4) Backslashes are interpreted literally, unless they
00540        immediately precede a double quotation mark.
00541 
00542     5) If backslashes immediately precede a double quotation mark,
00543        every pair of backslashes is interpreted as a literal
00544        backslash.  If the number of backslashes is odd, the last
00545        backslash escapes the next double quotation mark as
00546        described in rule 3.
00547     """
00548 
00549     # See
00550     # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
00551     # or search http://msdn.microsoft.com for
00552     # "Parsing C++ Command-Line Arguments"
00553     result = []
00554     needquote = False
00555     for arg in seq:
00556         bs_buf = []
00557 
00558         # Add a space to separate this argument from the others
00559         if result:
00560             result.append(' ')
00561 
00562         needquote = (" " in arg) or ("\t" in arg) or not arg
00563         if needquote:
00564             result.append('"')
00565 
00566         for c in arg:
00567             if c == '\\':
00568                 # Don't know if we need to double yet.
00569                 bs_buf.append(c)
00570             elif c == '"':
00571                 # Double backslashes.
00572                 result.append('\\' * len(bs_buf)*2)
00573                 bs_buf = []
00574                 result.append('\\"')
00575             else:
00576                 # Normal char
00577                 if bs_buf:
00578                     result.extend(bs_buf)
00579                     bs_buf = []
00580                 result.append(c)
00581 
00582         # Add remaining backslashes, if any.
00583         if bs_buf:
00584             result.extend(bs_buf)
00585 
00586         if needquote:
00587             result.extend(bs_buf)
00588             result.append('"')
00589 
00590     return ''.join(result)
00591 
00592 
00593 # Various tools for executing commands and looking at their output and status.
00594 #
00595 # NB This only works (and is only relevant) for POSIX.

Here is the caller graph for this function:


Variable Documentation

Initial value:
00001 ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput",
00002            "getoutput", "check_output", "CalledProcessError"]

Definition at line 414 of file subprocess.py.

list subprocess._active = []

Definition at line 432 of file subprocess.py.

subprocess._create_pipe = _posixsubprocess.cloexec_pipe

Definition at line 406 of file subprocess.py.

tuple subprocess._FD_CLOEXEC = getattr(fcntl, 'FD_CLOEXEC', 1)

Definition at line 396 of file subprocess.py.

tuple subprocess._has_poll = hasattr(select, 'poll')

Definition at line 379 of file subprocess.py.

tuple subprocess._PIPE_BUF = getattr(select, 'PIPE_BUF', 512)

Definition at line 394 of file subprocess.py.

Definition at line 634 of file subprocess.py.

Definition at line 386 of file subprocess.py.

int subprocess.MAXFD = os.sysconf("SC_OPEN_MAX")

Definition at line 428 of file subprocess.py.

tuple subprocess.mswindows = (sys.platform == "win32")

Definition at line 339 of file subprocess.py.

Definition at line 445 of file subprocess.py.

Definition at line 446 of file subprocess.py.