AlkantarClanX12

Your IP : 52.15.72.229


Current Path : /opt/alt/python34/lib64/python3.4/__pycache__/
Upload File :
Current File : //opt/alt/python34/lib64/python3.4/__pycache__/subprocess.cpython-34.pyc

�
e f%��@s4dZddlZejdkZddlZddlZddlZddlZddlZddl	Z	ddl
Z
yddlmZWn"e
k
r�ddlmZYnXGdd�de�ZGdd	�d	e�ZGd
d�de�Zer0ddlZddlZddlZGdd
�d
�Zn�ddlZddlZddlZyddlZWne
k
r�ddlZYnXeedd�Zeed�r�ejZn	ejZddddddddd	dg
Z er]ddlm!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(e j)dddddd d!d"g�Gd#d$�d$e*�Z+nyej,d%�Z-Wnd&Z-YnXgZ.d'd(�Z/d9Z0d:Z1d;Z2d,d-�Z3d.d/�Z4d0dd1d�Z5d2d�Z6d0dd3d�Z7d4d5�Z8d6d�Z9d7d�Z:e;�Z<Gd8d�de;�Z=dS)<aA.subprocess - Subprocesses with accessible I/O streams

This module allows you to spawn processes, connect to their
input/output/error pipes, and obtain their return codes.  This module
intends to replace several older modules and functions:

os.system
os.spawn*

Information about how the subprocess module can be used to replace these
modules and functions can be found below.



Using the subprocess module
===========================
This module defines one class called Popen:

class Popen(args, bufsize=-1, executable=None,
            stdin=None, stdout=None, stderr=None,
            preexec_fn=None, close_fds=True, shell=False,
            cwd=None, env=None, universal_newlines=False,
            startupinfo=None, creationflags=0,
            restore_signals=True, start_new_session=False, pass_fds=()):


Arguments are:

args should be a string, or a sequence of program arguments.  The
program to execute is normally the first item in the args sequence or
string, but can be explicitly set by using the executable argument.

On POSIX, with shell=False (default): In this case, the Popen class
uses os.execvp() to execute the child program.  args should normally
be a sequence.  A string will be treated as a sequence with the string
as the only item (the program to execute).

On POSIX, with shell=True: If args is a string, it specifies the
command string to execute through the shell.  If args is a sequence,
the first item specifies the command string, and any additional items
will be treated as additional shell arguments.

On Windows: the Popen class uses CreateProcess() to execute the child
program, which operates on strings.  If args is a sequence, it will be
converted to a string using the list2cmdline method.  Please note that
not all MS Windows applications interpret the command line the same
way: The list2cmdline is designed for applications using the same
rules as the MS C runtime.

bufsize will be supplied as the corresponding argument to the io.open()
function when creating the stdin/stdout/stderr pipe file objects:
0 means unbuffered (read & write are one system call and can return short),
1 means line buffered, any other positive value means use a buffer of
approximately that size.  A negative bufsize, the default, means the system
default of io.DEFAULT_BUFFER_SIZE will be used.

stdin, stdout and stderr specify the executed programs' standard
input, standard output and standard error file handles, respectively.
Valid values are PIPE, an existing file descriptor (a positive
integer), an existing file object, and None.  PIPE indicates that a
new pipe to the child should be created.  With None, no redirection
will occur; the child's file handles will be inherited from the
parent.  Additionally, stderr can be STDOUT, which indicates that the
stderr data from the applications should be captured into the same
file handle as for stdout.

On POSIX, if preexec_fn is set to a callable object, this object will be
called in the child process just before the child is executed.  The use
of preexec_fn is not thread safe, using it in the presence of threads
could lead to a deadlock in the child process before the new executable
is executed.

If close_fds is true, all file descriptors except 0, 1 and 2 will be
closed before the child process is executed.  The default for close_fds
varies by platform:  Always true on POSIX.  True when stdin/stdout/stderr
are None on Windows, false otherwise.

pass_fds is an optional sequence of file descriptors to keep open between the
parent and child.  Providing any pass_fds implicitly sets close_fds to true.

if shell is true, the specified command will be executed through the
shell.

If cwd is not None, the current directory will be changed to cwd
before the child is executed.

On POSIX, if restore_signals is True all signals that Python sets to
SIG_IGN are restored to SIG_DFL in the child process before the exec.
Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals.  This
parameter does nothing on Windows.

On POSIX, if start_new_session is True, the setsid() system call will be made
in the child process prior to executing the command.

If env is not None, it defines the environment variables for the new
process.

If universal_newlines is false, the file objects stdin, stdout and stderr
are opened as binary files, and no line ending conversion is done.

If universal_newlines is true, the file objects stdout and stderr are
opened as a text files, but lines may be terminated by any of '\n',
the Unix end-of-line convention, '\r', the old Macintosh convention or
'\r\n', the Windows convention.  All of these external representations
are seen as '\n' by the Python program.  Also, the newlines attribute
of the file objects stdout, stdin and stderr are not updated by the
communicate() method.

The startupinfo and creationflags, if given, will be passed to the
underlying CreateProcess() function.  They can specify things such as
appearance of the main window and priority for the new process.
(Windows only)


This module also defines some shortcut functions:

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 = subprocess.call(["ls", "-l"])

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:

    >>> subprocess.check_call(["ls", "-l"])
    0

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

    Execute the string 'cmd' in a shell with 'check_output' and
    return a 2-tuple (status, output). Universal newlines mode is used,
    meaning that the result with be decoded to a string.

    A trailing newline is stripped from the output.
    The exit status for the command can be interpreted
    according to the rules for the function 'wait'.  Example:

    >>> 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')

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:

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

check_output(*popenargs, **kwargs):
    Run command with arguments and return its output.

    If the exit code was non-zero it raises a CalledProcessError.  The
    CalledProcessError object will have the return code in the returncode
    attribute and output in the output attribute.

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

    >>> output = subprocess.check_output(["ls", "-l", "/dev/null"])

    There is an additional optional argument, "input", allowing you to
    pass a string to the subprocess's stdin.  If you use this argument
    you may not also use the Popen constructor's "stdin" argument.

Exceptions
----------
Exceptions raised in the child process, before the new program has
started to execute, will be re-raised in the parent.  Additionally,
the exception object will have one extra attribute called
'child_traceback', which is a string containing traceback information
from the child's point of view.

The most common exception raised is OSError.  This occurs, for
example, when trying to execute a non-existent file.  Applications
should prepare for OSErrors.

A ValueError will be raised if Popen is called with invalid arguments.

Exceptions defined within this module inherit from SubprocessError.
check_call() and check_output() will raise CalledProcessError if the
called process returns a non-zero return code.  TimeoutExpired
be raised if a timeout was specified and expired.


Security
--------
Unlike some other popen functions, this implementation will never call
/bin/sh implicitly.  This means that all characters, including shell
metacharacters, can safely be passed to child processes.


Popen objects
=============
Instances of the Popen class have the following methods:

poll()
    Check if child process has terminated.  Returns returncode
    attribute.

wait()
    Wait for child process to terminate.  Returns returncode attribute.

communicate(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).

    Note: The data read is buffered in memory, so do not use this
    method if the data size is large or unlimited.

The following attributes are also available:

stdin
    If the stdin argument is PIPE, this attribute is a file object
    that provides input to the child process.  Otherwise, it is None.

stdout
    If the stdout argument is PIPE, this attribute is a file object
    that provides output from the child process.  Otherwise, it is
    None.

stderr
    If the stderr argument is PIPE, this attribute is file object that
    provides error output from the child process.  Otherwise, it is
    None.

pid
    The process ID of the child process.

returncode
    The child return code.  A None value indicates that the process
    hasn't terminated yet.  A negative value -N indicates that the
    child was terminated by signal N (POSIX only).


Replacing older functions with the subprocess module
====================================================
In this section, "a ==> b" means that b can be used as a replacement
for a.

Note: All functions in this section fail (more or less) silently if
the executed program cannot be found; this module raises an OSError
exception.

In the following examples, we assume that the subprocess module is
imported with "from subprocess import *".


Replacing /bin/sh shell backquote
---------------------------------
output=`mycmd myarg`
==>
output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]


Replacing shell pipe line
-------------------------
output=`dmesg | grep hda`
==>
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]


Replacing os.system()
---------------------
sts = os.system("mycmd" + " myarg")
==>
p = Popen("mycmd" + " myarg", shell=True)
pid, sts = os.waitpid(p.pid, 0)

Note:

* Calling the program through the shell is usually not required.

* It's easier to look at the returncode attribute than the
  exitstatus.

A more real-world example would look like this:

try:
    retcode = call("mycmd" + " myarg", shell=True)
    if retcode < 0:
        print("Child was terminated by signal", -retcode, file=sys.stderr)
    else:
        print("Child returned", retcode, file=sys.stderr)
except OSError as e:
    print("Execution failed:", e, file=sys.stderr)


Replacing os.spawn*
-------------------
P_NOWAIT example:

pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
==>
pid = Popen(["/bin/mycmd", "myarg"]).pid


P_WAIT example:

retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
==>
retcode = call(["/bin/mycmd", "myarg"])


Vector example:

os.spawnvp(os.P_NOWAIT, path, args)
==>
Popen([path] + args[1:])


Environment example:

os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
==>
Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
�N�win32)�	monotonic)�timec@seZdZdS)�SubprocessErrorN)�__name__�
__module__�__qualname__�r	r	�//opt/alt/python34/lib64/python3.4/subprocess.pyrksrc@s1eZdZdZddd�Zdd�ZdS)�CalledProcessErrorz�This exception is raised when a process run by check_call() or
    check_output() returns a non-zero exit status.
    The exit status will be stored in the returncode attribute;
    check_output() will also store the output in the output attribute.
    NcCs||_||_||_dS)N)�
returncode�cmd�output)�selfrr
rr	r	r
�__init__ts		zCalledProcessError.__init__cCsd|j|jfS)Nz-Command '%s' returned non-zero exit status %d)r
r)rr	r	r
�__str__xszCalledProcessError.__str__)rrr�__doc__rrr	r	r	r
rnsrc@s1eZdZdZddd�Zdd�ZdS)�TimeoutExpiredz]This exception is raised when the timeout expires while waiting for a
    child process.
    NcCs||_||_||_dS)N)r
�timeoutr)rr
rrr	r	r
r�s		zTimeoutExpired.__init__cCsd|j|jfS)Nz'Command '%s' timed out after %s seconds)r
r)rr	r	r
r�szTimeoutExpired.__str__)rrrrrrr	r	r	r
r|src@s.eZdZdZdZdZdZdZdS)�STARTUPINFOrN)rrr�dwFlags�	hStdInput�
hStdOutput�	hStdError�wShowWindowr	r	r	r
r�s
rZPIPE_BUFi�PollSelector�Popen�PIPE�STDOUT�call�
check_call�getstatusoutput�	getoutput�check_output�DEVNULL)�CREATE_NEW_CONSOLE�CREATE_NEW_PROCESS_GROUP�STD_INPUT_HANDLE�STD_OUTPUT_HANDLE�STD_ERROR_HANDLE�SW_HIDE�STARTF_USESTDHANDLES�STARTF_USESHOWWINDOWr%r&r'r(r)r*r+r,c@sLeZdZdZejdd�Zdd�Zdd�ZeZ	eZ
dS)	�HandleFcCs#|jsd|_||�ndS)NT)�closed)r�CloseHandler	r	r
�Close�s		zHandle.ClosecCs,|jsd|_t|�Std��dS)NTzalready closed)r.�int�
ValueError)rr	r	r
�Detach�s		
z
Handle.DetachcCsdt|�S)Nz
Handle(%d))r1)rr	r	r
�__repr__�szHandle.__repr__N)rrrr.�_winapir/r0r3r4�__del__rr	r	r	r
r-�sr-�SC_OPEN_MAX�cCsixbtdd�D]P}|jdtj�}|dk	rytj|�Wqatk
r]YqaXqqWdS)N�
_deadstate)�_active�_internal_poll�sys�maxsize�remover2)Zinst�resr	r	r
�_cleanup�s
r@���cGs1x*y||�SWqtk
r(wYqXqWdS)N)�InterruptedError)�func�argsr	r	r
�_eintr_retry_call�s

rGcCs�i	dd6dd6dd6dd6d	d
6dd6d
d6dd6dd6}g}xP|j�D]B\}}ttj|�}|dkrX|jd||�qXqXWx"tjD]}|jd|�q�W|S)znReturn a list of command-line arguments reproducing the current
    settings in sys.flags and sys.warnoptions.�d�debug�O�optimize�B�dont_write_bytecode�s�no_user_site�S�no_site�E�ignore_environment�v�verbose�b�
bytes_warning�q�quietr�-z-W)�items�getattrr<�flags�append�warnoptions)Zflag_opt_maprFZflagZoptrTr	r	r
�_args_from_interpreter_flags�s$
r`rcOsRt||��=}y|jd|�SWn|j�|j��YnXWdQXdS)z�Run command with arguments.  Wait for command to complete or
    timeout, then return the returncode attribute.

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

    retcode = call(["ls", "-l"])
    rN)r�wait�kill)r�	popenargs�kwargs�pr	r	r
rs

cOsSt||�}|rO|jd�}|dkr=|d}nt||��ndS)aORun 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 call function.  Example:

    check_call(["ls", "-l"])
    rFNr)r�getr)rcrd�retcoder
r	r	r
r s

cOs;d|krtd��nd|kr`d|krBtd��n|d}|d=t|d<nd}tdt||���}y|j|d|�\}}Wndtk
r�|j�|j�\}}t|j|d|��Yn|j�|j��YnX|j�}|r1t	||jd|��nWdQX|S)	a�Run command with arguments and return its output.

    If the exit code was non-zero it raises a CalledProcessError.  The
    CalledProcessError object will have the return code in the returncode
    attribute and output in the output attribute.

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

    >>> check_output(["ls", "-l", "/dev/null"])
    b'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'

    The stdout argument is not allowed as it is used internally.
    To capture standard error in the result, use stderr=STDOUT.

    >>> check_output(["/bin/sh", "-c",
    ...               "ls -l non_existent_file ; exit 0"],
    ...              stderr=STDOUT)
    b'ls: non_existent_file: No such file or directory\n'

    There is an additional optional argument, "input", allowing you to
    pass a string to the subprocess's stdin.  If you use this argument
    you may not also use the Popen constructor's "stdin" argument, as
    it too will be used internally.  Example:

    >>> check_output(["sed", "-e", "s/foo/bar/"],
    ...              input=b"when in the course of fooman events\n")
    b'when in the course of barman events\n'

    If universal_newlines=True is passed, the return value will be a
    string rather than bytes.
    �stdoutz3stdout argument not allowed, it will be overridden.�input�stdinz/stdin and input arguments may not both be used.Nrr)
r2rr�communicaterrbrFra�pollr)rrcrdZ	inputdataZprocessrZ
unused_errrgr	r	r
r#2s0 





!cCsGg}d}x+|D]#}g}|r5|jd�nd|kpQd|kpQ|}|rj|jd�nx�|D]�}|dkr�|j|�qq|dkr�|jdt|�d�g}|jd�qq|r�|j|�g}n|j|�qqW|r|j|�n|r|j|�|jd�qqWdj|�S)	a�
    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.
    F� �	�"�\rBz\"�)r^�len�extend�join)�seq�resultZ	needquote�argZbs_buf�cr	r	r
�list2cmdlinems4


	
rycCs�y(t|dddddt�}d}Wn7tk
ra}z|j}|j}WYdd}~XnX|d	d�dkr�|dd
�}n||fS)a�    Return (status, output) of executing cmd in a shell.

    Execute the string 'cmd' in a shell with 'check_output' and
    return a 2-tuple (status, output). Universal newlines mode is used,
    meaning that the result with be decoded to a string.

    A trailing newline is stripped from the output.
    The exit status for the command can be interpreted
    according to the rules for the 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')
    �shellT�universal_newlines�stderrrNrA�
���r~)r#rrrr)r
�dataZstatusZexr	r	r
r!�s
	cCst|�dS)a%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'
    rA)r!)r
r	r	r
r"�s
c@s#eZdZdZd=dddddeddddddddfdd�Zdd	�Zd
d�Zdd
�Ze	j
dd�Zdd�Zdddd�Z
dd�Zdd�Zdd�Zer\dd�Zdd�Zdd�Zdejejejd d!�Zddd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�ZeZn�d,d�Zd-d.�Z d/d�Ze!j"e!j#e!j$e!j%d0d1�Z&de!j'e!j(e)j*d2d!�Zd3d4�Z+ddd5d#�Zd6d'�Zd7d8�Z,d9d)�Zd:d+�Zd;d<�ZdS)>rFrANrTcCs�t�tj�|_d|_d|_|dkr=d}nt|t�s[td��nt	r�|dk	r|t
d��n|dk	p�|dk	p�|dk	}|tkr�|r�d}q�d}qS|rS|rSt
d��qSnq|tkr�d}n|r|rtj
dt�d}n|
dk	r8t
d	��n|d
krSt
d��n||_d|_d|_d|_d|_d|_||_|j|||�\}}}}}}t	r7|dkr�tj|j�d
�}n|dkr
tj|j�d
�}n|dkr7tj|j�d
�}q7n|dkr�tj|d|�|_|r�tj|jd
dd|dk�|_q�n|dkr�tj|d|�|_|r�tj|j�|_q�n|dkrtj|d|�|_|rtj|j�|_qnd|_yD|j||||||
||
||	||||||||�WnxLtd|j|j|jf�D])}y|j �Wq�t!k
r�Yq�Xq�W|jsyg}|t"kr�|j#|�n|t"kr|j#|�n|t"kr|j#|�nt$|d�r?|j#|j%�nx7|D],}yt&j |�WqFt!k
rqYqFXqFWn�YnXdS)zCreate new Popen instance.NFrAzbufsize must be an integerz0preexec_fn is not supported on Windows platformsTzSclose_fds is not supported on Windows platforms if you redirect stdin/stdout/stderrzpass_fds overriding close_fds.z2startupinfo is only supported on Windows platformsrz4creationflags is only supported on Windows platforms�wbZ
write_through�line_buffering�rb�_devnullr~r~r~r~r~r~r~)'r@�	threadingZLock�
_waitpid_lock�_input�_communication_started�
isinstancer1�	TypeError�	mswindowsr2�_PLATFORM_DEFAULT_CLOSE_FDS�warnings�warn�RuntimeWarningrFrjrhr|�pidrr{�_get_handles�msvcrtZopen_osfhandler3�io�open�
TextIOWrapper�_closed_child_pipe_fds�_execute_child�filter�close�OSErrorrr^�hasattrr��os)rrF�bufsize�
executablerjrhr|�
preexec_fn�	close_fdsrz�cwd�envr{�startupinfo�
creationflags�restore_signals�start_new_session�pass_fdsZ
any_stdio_set�p2cread�p2cwrite�c2pread�c2pwrite�errread�errwrite�fZto_close�fdr	r	r
r�s�						
								'			(
		

zPopen.__init__cCs+|j|�}|jdd�jdd�S)Nz
r}�
)�decode�replace)rr�encodingr	r	r
�_translate_newlinestszPopen._translate_newlinescCs|S)Nr	)rr	r	r
�	__enter__xszPopen.__enter__c
Csa|jr|jj�n|jr2|jj�nz|jrN|jj�nWd|j�XdS)N)rhr�r|rjra)r�type�value�	tracebackr	r	r
�__exit__{s			zPopen.__exit__cCsL|js
dS|jd|�|jdkrHtdk	rHtj|�ndS)Nr9)�_child_createdr;rr:r^)rZ_maxsizer	r	r
r6�s
	z
Popen.__del__cCs4t|d�s-tjtjtj�|_n|jS)Nr�)r�r�r��devnull�O_RDWRr�)rr	r	r
�_get_devnull�szPopen._get_devnullcCs�|jr|rtd��n|dkrR|jrR|j|j|jgjd�dkrRd}d}|jr�|r�y|jj|�Wq�tk
r�}z/|jtj	kr�|jtj
kr��nWYdd}~Xq�Xn|jj�nV|jrt|jj
�}|jj�n+|jrEt|jj
�}|jj�n|j�ni|dk	rnt�|}nd}z|j|||�\}}Wdd|_X|jd|j|��}||fS)acInteract 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
        bytes to be sent to the child process, or None, if no data
        should be sent to the child.

        communicate() returns a tuple (stdout, stderr).z.Cannot send input after starting communicationNrBTr)r�r2rjrhr|�count�writer��errno�EPIPE�EINVALr�rG�readra�_time�_communicate�_remaining_time)rrirrhr|�e�endtime�stsr	r	r
rk�s:	'	$		

zPopen.communicatecCs
|j�S)N)r;)rr	r	r
rl�sz
Popen.pollcCs|dkrdS|t�SdS)z5Convenience for _communicate when computing timeouts.N)r�)rr�r	r	r
r��szPopen._remaining_timecCs8|dkrdSt�|kr4t|j|��ndS)z2Convenience for checking if a timeout has expired.N)r�rrF)rr��orig_timeoutr	r	r
�_check_timeout�szPopen._check_timeoutcCs�|dkr(|dkr(|dkr(d
Sd
\}}d\}}d\}}	|dkr�tjtj�}|dkrGtjdd�\}}
t|�}tj|
�qGn�|tkr�tjdd�\}}t|�t|�}}nZ|tkrtj	|j
��}n6t|t�r2tj	|�}ntj	|j
��}|j|�}|dkr�tjtj�}|dkrQtjdd�\}
}t|�}tj|
�qQn�|tkr�tjdd�\}}t|�t|�}}nZ|tkrtj	|j
��}n6t|t�r<tj	|�}ntj	|j
��}|j|�}|dkr�tjtj�}	|	dkrptjdd�\}
}	t|	�}	tj|
�qpn�|tkrtjdd�\}}	t|�t|	�}}	no|tkr|}	nZ|tkr:tj	|j
��}	n6t|t�r[tj	|�}	ntj	|j
��}	|j|	�}	||||||	fS)z|Construct and return tuple with IO objects:
            p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
            NrArr~r~r~r~r~r~)r~r~r~r~r~r~r~r~)r~r~r~r~)r~r~r~r~)r~r~)r5ZGetStdHandler'Z
CreatePiper-r/rr$r�Z
get_osfhandler�r�r1�fileno�_make_inheritabler(r)r)rrjrhr|r�r�r�r�r�r��_r	r	r
r��sn$	zPopen._get_handlescCs7tjtj�|tj�ddtj�}t|�S)z2Return a duplicate of handle, which is inheritablerrA)r5ZDuplicateHandleZGetCurrentProcessZDUPLICATE_SAME_ACCESSr-)rZhandle�hr	r	r
r�(s
zPopen._make_inheritablecCs�|std��t|t�s1t|�}n|dkrIt�}nd	|||fkr�|jtjO_||_||_	||_
n|
r�|jtjO_tj|_
tjjdd�}dj||�}nz>tj||ddt|�|	|||�	\}}}}Wd|d
kr6|j�n|dkrO|j�n|dkrh|j�nt|d�r�tj|j�nXd|_t|�|_||_tj|�dS)
z$Execute program (MS Windows version)z"pass_fds not supported on Windows.NrAZCOMSPECzcmd.exez
{} /c "{}"r�Tr~r~r~r~)�AssertionErrorr��strryrrr5r+rrrr,r*rr��environrf�formatZ
CreateProcessr1r0r�r�r�r�r-�_handler�r/)rrFr�r�r�r�r�r�r�r�rzr�r�r�r�r�r�Zunused_restore_signalsZunused_start_new_sessionZcomspecZhpZhtr��tidr	r	r
r�1sF			



		zPopen._execute_childcCsF|jdkr?||jd�|kr?||j�|_q?n|jS)z�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.

            Nr)rr�)rr9Z_WaitForSingleObjectZ_WAIT_OBJECT_0Z_GetExitCodeProcessr	r	r
r;nszPopen._internal_pollcCs�|dk	r|j|�}n|dkr6tj}nt|d�}|jdkr�tj|j|�}|tjkr�t|j	|��ntj
|j�|_n|jS)zOWait for child process to terminate.  Returns returncode
            attribute.Ni�)r�r5ZINFINITEr1r�WaitForSingleObjectr�ZWAIT_TIMEOUTrrF�GetExitCodeProcess)rrr�Ztimeout_millisrvr	r	r
ras	z
Popen.waitcCs!|j|j��|j�dS)N)r^r�r�)rZfh�bufferr	r	r
�
_readerthread�szPopen._readerthreadcCs�|jrht|d�rhg|_tjd|jd|j|jf�|_d|j_|jj�n|j	r�t|d�r�g|_
tjd|jd|j	|j
f�|_d|j_|jj�n|jrs|dk	rcy|jj
|�Wqctk
r_}zD|jtjkr#n*|jtjkrJ|j�dk	rJn�WYdd}~XqcXn|jj�n|jdk	r�|jj|j|��|jj�r�t|j|��q�n|j	dk	r|jj|j|��|jj�rt|j|��qnd}d}|jr?|j}|jj�n|j	ra|j
}|j	j�n|dk	rz|d}n|dk	r�|d}n||fS)N�_stdout_buff�targetrFT�_stderr_buffr)rhr�r�r�ZThreadr�Z
stdout_threadZdaemon�startr|r�Z
stderr_threadrjr�r�r�r�r�rlr�rtr�Zis_aliverrF)rrir�r�r�rhr|r	r	r
r��sZ							

zPopen._communicatecCs�|jdk	rdS|tjkr/|j�ne|tjkrWtj|jtj�n=|tjkrtj|jtj�nt	dj
|���dS)zSend a signal to the process.NzUnsupported signal: {})r�signal�SIGTERM�	terminateZCTRL_C_EVENTr�rbr�ZCTRL_BREAK_EVENTr2r�)r�sigr	r	r
�send_signal�s
zPopen.send_signalcCss|jdk	rdSytj|jd�WnBtk
rntj|j�}|tjkra�n||_YnXdS)zTerminates the process.NrA)rr5ZTerminateProcessr��PermissionErrorr�ZSTILL_ACTIVE)r�rcr	r	r
r��s
zPopen.terminatec
Cs�d\}}d\}}d\}}	|dkr3n`|tkrTtj�\}}n?|tkro|j�}n$t|t�r�|}n|j�}|dkr�n`|tkr�tj�\}}n?|tkr�|j�}n$t|t�r�|}n|j�}|dkrnu|tkr2tj�\}}	nT|tkrG|}	n?|tkrb|j�}	n$t|t�rz|}	n|j�}	||||||	fS)z|Construct and return tuple with IO objects:
            p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
            rANr~r~)r~r~r~r~)r~r~r~r~)r~r~)	rr��piper$r�r�r1r�r)
rrjrhr|r�r�r�r�r�r�r	r	r
r��sF				cCsid}x=t|�D]/}||krtj||�|d}qqW|tkretj|t�ndS)NrCrA)�sortedr��
closerange�MAXFD)r�fds_to_keepZstart_fdr�r	r	r
�
_close_fds.szPopen._close_fdsc'(st|ttf�r!|g}nt|�}|
rYddg|}�rY�|d<qYn�dkrr|d�n�}tj�\}}g}x,|dkr�|j|�tj|�}q�Wx|D]}tj|�q�WzwzC|dk	r]g}xk|j	�D]T\}}tj
|�}d|kr8td��n|j|dtj
|��qWnd}tj
���tjj
��r��f}n(t�fdd	�tj|�D��}t|�}|j|�tj|||t|�|||||
||||||||�|_d
|_Wdtj|�Xt|dd�}|dkrz|dkrz||krztj|�n|dkr�|
dkr�||kr�tj|�n|dkr�|dkr�||kr�tj|�n|dk	r�tj|�nd
|_t�}x@ttj|d
�}||7}|sKt|�d
krPqqWWdtj|�X|ryttj|jd�Wn=tk
r�} z| jtj kr��nWYdd} ~ XnXy|j!dd�\}!}"}#Wn.tk
rd}!d}"dt"|�}#YnXtt#|!j$d�t%�}$|#j$dd�}#t&|$t�r�|"r�t'|"d�}%|#dk}&|&r�d}#n|%dkr�tj(|%�}#|%tj)kr�|&r�|#dt"|�7}#q�|#dt"|�7}#q�n|$|%|#��n|$|#��ndS) zExecute program (POSIX version)z/bin/shz-crNrC�=z!illegal environment variable namec3s-|]#}tjjtj|���VqdS)N)r��pathrt�fsencode)�.0�dir)r�r	r
�	<genexpr>psz'Popen._execute_child.<locals>.<genexpr>Tr�rAiP��:rBsSubprocessError�0sBad exception data from child: �ascii�errors�
surrogatepass�Znoexecrqz: r~r~r~r~r~r~)*r�r��bytes�listr�r�r^�dupr�r[r�r2r��dirname�tuple�
get_exec_path�set�add�_posixsubprocessZ	fork_execr�r�r�r\r��	bytearrayrGr�rr�waitpidr�r��ECHILD�split�repr�builtinsr�r�
issubclassr1�strerror�ENOENT)'rrFr�r�r�r�r�r�r�r�rzr�r�r�r�r�r�r�r�Zorig_executableZerrpipe_readZ
errpipe_writeZlow_fds_to_closeZlow_fdZenv_list�krTZexecutable_listr�Z
devnull_fdZerrpipe_data�partr�Zexception_nameZ	hex_errnoZerr_msgZchild_exception_typeZ	errno_numZchild_exec_never_calledr	)r�r
r�8s�	


%

$$$		

		cCsM||�r||�|_n*||�r=||�|_ntd��dS)z:All callers to this function MUST hold self._waitpid_lock.zUnknown child exit status!N)rr)rr�Z_WIFSIGNALEDZ	_WTERMSIGZ
_WIFEXITEDZ_WEXITSTATUSr	r	r
�_handle_exitstatus�s
zPopen._handle_exitstatuscCs�|jdkr�|jjd�s%dSz�yQ|jdk	rA|jS||j|�\}}||jkrx|j|�nWnXtk
r�}z8|dk	r�||_n|j|kr�d|_nWYdd}~XnXWd|jj�Xn|jS)z�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).

            NFr)rr��acquirer�r
r�r��release)rr9Z_waitpidZ_WNOHANGZ_ECHILDr�r�r�r	r	r
r;�s 	#cCs{y"ttj|j|�\}}WnLtk
rp}z,|jtjkrO�n|j}d}WYdd}~XnX||fS)z:All callers to this function MUST hold self._waitpid_lock.rN)rGr�rr�r�r�r)rZ
wait_flagsr�r�r�r	r	r
�	_try_wait�s"	zPopen._try_waitcCs�|jdk	r|jS|dk	s.|dk	rk|dkrJt�|}qk|dkrk|j|�}qkn|dk	rpd}x]|jjd�rzp|jdk	r�Pn|jtj�\}}||jks�|dks�t	�||jkr|j
|�PnWd|jj�Xn|j|�}|dkrFt|j
|��nt|d|d�}tj|�q�Wnmxj|jdkr�|j�L|jdk	r�Pn|jd�\}}||jkr�|j
|�nWdQXqsW|jS)zOWait for child process to terminate.  Returns returncode
            attribute.Ng����Mb@?FrrBg�������?)rr�r�r�rr
r��WNOHANGr�r�r
rrrF�minrZsleep)rrr�Zdelayr�r�Z	remainingr	r	r
ra�sB!

cCs|jr9|jr9|jj�|s9|jj�q9nd}d}|js�i|_|jrsg|j|j<n|jr�g|j|j<q�n|jr�|j|j}n|jr�|j|j}n|j|�|jr�t	|j�}nt
��N}|jr&|r&|j|jtj
�n|jrH|j|jtj�n|jrj|j|jtj�nx�|j�rD|j|�}|dk	r�|dkr�t|j|��n|j|�}	|j||�xj|	D]b\}
}|
j|jkr�||j|jt�}y"|jtj|
j|�7_WnZtk
r�}
z:|
jtjkr||j|
j�|
jj�n�WYdd}
~
Xq=X|jt|j�kr=|j|
j�|
jj�q=q�|
j|j|jfkr�tj |
jd�}|s#|j|
j�|
jj�n|j|
jj!|�q�q�WqmWWdQX|j"d|j|��|dk	r�dj#|�}n|dk	r�dj#|�}n|j$r�|dk	r�|j%||jj&�}n|dk	r�|j%||jj&�}q�n||fS)Nri�r�)'rjr��flushr�Z_fileobj2outputrhr|�_save_inputr��
memoryview�_PopenSelector�register�	selectorsZEVENT_WRITEZ
EVENT_READZget_mapr�rrF�selectr�Zfileobj�
_input_offset�	_PIPE_BUFr�r�r�r�r�r�Z
unregisterrrr�r^rartr{r�r�)rrir�r�rhr|Z
input_viewZselectorrZready�keyZevents�chunkr�rr	r	r
r�.s�
						
				"(			cCsd|jr`|jdkr`d|_||_|jr`|dk	r`|jj|jj�|_q`ndS)Nr)rjr�rr{�encoder�)rrir	r	r
r�s
		zPopen._save_inputcCs)|jdkr%tj|j|�ndS)zSend a signal to the process.N)rr�rbr�)rr�r	r	r
r��scCs|jtj�dS)z/Terminate the process with SIGTERM
            N)r�r�r�)rr	r	r
r��scCs|jtj�dS)z*Kill the process with SIGKILL
            N)r�r��SIGKILL)rr	r	r
rb�sz
Popen.killr~)-rrrr�r�rr�r�r�r<r=r6r�rkrlr�r�r�r�r�r�r5r�Z
WAIT_OBJECT_0r�r;rar�r�r�r�rbr�r��WIFSIGNALED�WTERMSIG�	WIFEXITED�WEXITSTATUSr
rrr�rr
rr	r	r	r
r�s\	�
2H	=B	3
�
	"1\r~������)>rr<�platformr�r�r�rr�rr�r�rr��ImportError�	Exceptionrrrr�r�r5rr�rrZdummy_threadingr\rr�rrZSelectSelector�__all__r%r&r'r(r)r*r+r,rsr1r-�sysconfr�r:r@rrr$rGr`rr r#ryr!r"�objectr�rr	r	r	r
�<module>Ysx

	:
;I