B Y6d1@s`dZddlZejdkZddlZddlZddlZddlZddlZddl Z ddl Z ddlm Z Gddde ZGdddeZGd d d eZerddlZddlZddlZGd d d ZnDddlZddlZddlZddlZeed dZeedrejZnejZddddddddddddd dgZerddlmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0e1ddddd d!d"d#d d$d%d&d'd(d)d*d+d,d-gGd.d/d/e2Z3erdZ4d0d1Z5n gZ4d2d1Z5d3Z6d4Z7d5Z8d6d7Z9d8d9Z:dd:d;dZ;ddde>Z?dd?dd?d@dAdZ@dBdCZAdDdZBdEdZCGdFdde>ZDdS)GaSubprocesses with accessible I/O streams This module allows you to spawn processes, connect to their input/output/error pipes, and obtain their return codes. For a complete description of this module see the Python documentation. Main API ======== run(...): Runs a command, waits for it to complete, then returns a CompletedProcess instance. Popen(...): A class for flexibly executing a command in a new process Constants --------- DEVNULL: Special value that indicates that os.devnull should be used PIPE: Special value that indicates a pipe should be created STDOUT: Special value that indicates that stderr should go to stdout Older API ========= call(...): Runs a command, waits for it to complete, then returns the return code. check_call(...): Same as call() but raises CalledProcessError() if return code is not 0 check_output(...): Same as check_call() but returns the contents of stdout instead of a return code getoutput(...): Runs a command in the shell, waits for it to complete, then returns the output getstatusoutput(...): Runs a command in the shell, waits for it to complete, then returns a (exitcode, output) tuple Nwin32) monotonicc@s eZdZdS)SubprocessErrorN)__name__ __module__ __qualname__rr&/usr/local/lib/python3.7/subprocess.pyr9src@s<eZdZdZd ddZddZeddZejd dZdS) CalledProcessErrorzRaised when run() is called with check=True and the process returns a non-zero exit status. Attributes: cmd, returncode, stdout, stderr, output NcCs||_||_||_||_dS)N) returncodecmdoutputstderr)selfr r r rrrr __init__CszCalledProcessError.__init__cCsb|jrN|jdkrNyd|jt|j fStk rJd|j|j fSXnd|j|jfSdS)NrzCommand '%s' died with %r.z)Command '%s' died with unknown signal %d.z.Command '%s' returned non-zero exit status %d.)r r signalSignals ValueError)rrrr __str__IszCalledProcessError.__str__cCs|jS)z+Alias for output attribute, to match stderr)r )rrrr stdoutUszCalledProcessError.stdoutcCs ||_dS)N)r )rvaluerrr rZs)NN) rrr__doc__rrpropertyrsetterrrrr r <s   r c@s<eZdZdZd ddZddZeddZejd dZdS) TimeoutExpiredzThis exception is raised when the timeout expires while waiting for a child process. Attributes: cmd, output, stdout, stderr, timeout NcCs||_||_||_||_dS)N)r timeoutr r)rr rr rrrr rhszTimeoutExpired.__init__cCsd|j|jfS)Nz'Command '%s' timed out after %s seconds)r r)rrrr rnszTimeoutExpired.__str__cCs|jS)N)r )rrrr rrszTimeoutExpired.stdoutcCs ||_dS)N)r )rrrrr rvs)NN) rrrrrrrrrrrrr ras   rc@s,eZdZdddddddddZddZdS) STARTUPINFOrN)dwFlags hStdInput hStdOutput hStdError wShowWindowlpAttributeListcCs0||_||_||_||_||_|p(dgi|_dS)N handle_list)rrrr r!r")rrrrr r!r"rrr rs zSTARTUPINFO.__init__cCs@|j}d|kr"t|d|d<t|j|j|j|j|j|dS)Nr#)rrrr r!r") r"copylistrrrrr r!)rZ attr_listrrr _copys zSTARTUPINFO._copy)rrrrr&rrrr rsrPIPE_BUFi PollSelectorPopenPIPESTDOUTcall check_callgetstatusoutput getoutput check_outputrunDEVNULLCompletedProcess)CREATE_NEW_CONSOLECREATE_NEW_PROCESS_GROUPSTD_INPUT_HANDLESTD_OUTPUT_HANDLESTD_ERROR_HANDLESW_HIDESTARTF_USESTDHANDLESSTARTF_USESHOWWINDOWABOVE_NORMAL_PRIORITY_CLASSBELOW_NORMAL_PRIORITY_CLASSHIGH_PRIORITY_CLASSIDLE_PRIORITY_CLASSNORMAL_PRIORITY_CLASSREALTIME_PRIORITY_CLASSCREATE_NO_WINDOWDETACHED_PROCESSCREATE_DEFAULT_ERROR_MODECREATE_BREAKAWAY_FROM_JOBr4r5r6r7r8r9r:r;r<r=r>r?r@rArBrCrDrEc@s6eZdZdZejfddZddZddZeZ eZ dS) HandleFcCs|jsd|_||dS)NT)closed)r CloseHandlerrr Closesz Handle.ClosecCs |jsd|_t|StddS)NTzalready closed)rGintr)rrrr Detachsz Handle.DetachcCsd|jjt|fS)Nz%s(%d)) __class__rrJ)rrrr __repr__szHandle.__repr__N) rrrrG_winapirHrIrKrM__del__rrrrr rFs rFcCsdS)Nrrrrr _cleanupsrPc Cs`tdkr dSxNtddD]>}|jtjd}|dk ryt|Wqtk rVYqXqWdS)N) _deadstate)_active_internal_pollsysmaxsizeremover)instresrrr rPscCs*g}tjj}|dkr&|dd||S)zgReturn a list of command-line arguments reproducing the current optimization settings in sys.flags.r-O)rTflagsoptimizeappend)argsrrrr "_optim_args_from_interpreter_flagss rbc Csbddddddd}t}x:|D].\}}ttj|}|dkr"|d ||q"Wtjjrh|d n$tjjrz|d tjjr|d tj d d }tjj }ttdi}d|k}|dkr| dn|r| d|r| dx|D]}|d|qW|r| dxJdD]B}||kr||} | dkr>|} n d|| f} | d| fqW|S)z}Return a list of command-line arguments reproducing the current settings in sys.flags, sys.warnoptions and sys._xoptions.dBSvbq)debugdont_write_bytecodeno_siteverbose bytes_warningquietrr\z-Iz-Ez-sN _xoptionsdevzerror::BytesWarningzdefault::BytesWarningdefaultz-W)z-Xrp)Z faulthandler tracemallocZ importtimeZshowalloccountZ showrefcountutf8Tz%s=%sz-X) rbitemsgetattrrTr^r`isolatedignore_environment no_user_site warnoptionsrmrVextend) Z flag_opt_mapraflagoptrfZwarnoptsrmZxoptionsdev_moderargrrr _args_from_interpreter_flagssN              r)rc Os>t||*}y |j|dS|YnXWdQRXdS)zRun 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)waitkill)r popenargskwargsprrr r,Ks   cOs6t||}|r2|d}|dkr(|d}t||dS)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"]) raNr)r,getr )rrretcoder rrr r-\s   cOsTd|krtdd|kr<|ddkr<|ddr4dnd|d<t|t|d d |jS) aRun 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' By default, all communication is in bytes, and therefore any "input" should be bytes, and the return value will be bytes. If in text mode, any "input" should be a string, and the return value will be a string decoded according to locale encoding, or by "encoding" if set. Text mode is triggered by setting any of text, encoding, errors or universal_newlines. rz3stdout argument not allowed, it will be overridden.inputNuniversal_newlinesFT)rrcheck)rrr1r*r)rrrrrr r0os #c@s*eZdZdZd ddZddZddZdS) r3aEA process that has finished running. This is returned by run(). Attributes: args: The list or str args passed to run(). returncode: The exit code of the process, negative for signals. stdout: The standard output (None if not captured). stderr: The standard error (None if not captured). NcCs||_||_||_||_dS)N)rar rr)rrar rrrrr rszCompletedProcess.__init__cCshd|jd|jg}|jdk r4|d|j|jdk rP|d|jdt|jd|S)Nz args={!r}zreturncode={!r}z stdout={!r}z stderr={!r}z{}({})z, ) formatrar rr`rtyperjoin)rrarrr rMs   zCompletedProcess.__repr__cCs |jrt|j|j|j|jdS)z6Raise CalledProcessError if the exit code is non-zero.N)r r rarr)rrrr check_returncodesz!CompletedProcess.check_returncode)NN)rrrrrrMrrrrr r3s   F)rcapture_outputrrc Os |dk r&|ddk rtdt|d<|r^|ddk sF|ddk rNtdt|d<t|d<t||}y|j||d\}}Wn^tk r} z,|tr|\| _| _ n| Wdd} ~ XYn|YnX| } |r| rt | |j ||dWdQRXt|j | ||S) aKRun command with arguments and return a CompletedProcess instance. The returned instance will have attributes args, returncode, stdout and stderr. By default, stdout and stderr are not captured, and those attributes will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them. If check is True and the exit code was non-zero, it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute, and output & stderr attributes if those streams were captured. If timeout is given, and the process takes too long, a TimeoutExpired exception will be raised. There is an optional argument "input", allowing you to pass bytes or 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 will be used internally. By default, all communication is in bytes, and therefore any "input" should be bytes, and the stdout and stderr will be bytes. If in text mode, any "input" should be a string, and stdout and stderr will be strings decoded according to locale encoding, or by "encoding" if set. Text mode is triggered by setting any of text, encoding, errors or universal_newlines. The other arguments are the same as for the Popen constructor. Nstdinz/stdin and input arguments may not both be used.rrz@stdout and stderr arguments may not be used with capture_output.)r)r r)rrr*r) communicaterr _mswindowsrrrpollr rar3) rrrrrrprocessrrexcrrrr r1s4  cCsg}d}x|D]}g}|r$|dd|kp8d|kp8| }|rH|dxj|D]b}|dkrf||qN|dkr|dt|dg}|dqN|r||g}||qNW|r|||r|||dqWd|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  "\z\"r)r`lenr{r)seqresultZ needquoterZbs_bufcrrr list2cmdlines4         rc Cslyt|ddtd}d}Wn.tk rF}z|j}|j}Wdd}~XYnX|dddkrd|dd}||fS)aReturn (exitcode, output) of executing cmd in a shell. Execute the string 'cmd' in a shell with 'check_output' and return a 2-tuple (status, output). The locale encoding is used to decode the output and process newlines. 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') (1, 'cat: /bin/junk: No such file or directory') >>> subprocess.getstatusoutput('/bin/junk') (127, 'sh: /bin/junk: not found') >>> subprocess.getstatusoutput('/bin/kill $$') (-15, '') T)shelltextrrNrY )r0r+r r r )r dataexitcodeZexrrr r.Ms cCs t|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' rq)r.)r rrr r/ls c@seZdZdZdZdGddddd d Zed d Zejd d ZddZ ddZ ddZ e j ejfddZddZddZdHddZddZddZdId d!ZdJd"d#Zerd$d%Zd&d'Zd(d)Zd*d+Zdejejej fd,d-Z!d.d/Z"d0d1Z#d2d3Z$d4d5Z%d6d7Z&e&Z'nd8d%Zd9d+Ze(j)e(j*e(j+e(j,e(j-e(j.fd:d;Z/de(j0e(j1e2j3fdZ4d?d/Z"d@d3Z$dAdBZ5dCd5Z%dDd7Z&dEdFZ'dS)Kr)a Execute a child program in a new process. For a complete description of the arguments see the Python documentation. Arguments: args: A string, or a sequence of program arguments. bufsize: supplied as the buffering argument to the open() function when creating the stdin/stdout/stderr pipe file objects executable: A replacement program to execute. stdin, stdout and stderr: These specify the executed programs' standard input, standard output and standard error file handles, respectively. preexec_fn: (POSIX only) An object to be called in the child process just before the child is executed. close_fds: Controls closing or inheriting of file descriptors. shell: If true, the command will be executed through the shell. cwd: Sets the current directory before the child is executed. env: Defines the environment variables for the new process. text: If true, decode stdin, stdout and stderr using the given encoding (if set) or the system default otherwise. universal_newlines: Alias of text, provided for backwards compatibility. startupinfo and creationflags (Windows only) restore_signals (POSIX only) start_new_session (POSIX only) pass_fds (POSIX only) encoding and errors: Text mode encoding and error handling to use for file objects stdin, stdout and stderr. Attributes: stdin, stdout, stderr, pid, returncode FrYNTrr)encodingerrorsrcCsZtt|_d|_d|_|dkr(d}t|ts:tdt rP|dk rt dn8|rh|sht dt d}| dk rxt d|d krt d ||_d|_d|_d|_d|_d|_||_||_|dk r| dk rt| t|krtd ||||\}}}}}}t rN|dkrt|d }|dkr4t|d }|dkrNt|d }|pb|pb|pb| |_d |_d|_y|dkrt |d ||_|jrtj!|jd|dk||d|_|dkrt |d||_|jrtj!|j||d|_|dkrt |d||_|jrtj!|j||d|_|"|||||| | | || ||||||||WnxDt#d|j|j|jfD]*}y |$Wnt%k rYnXqnW|jsNg}|t&kr|'||t&kr|'||t&kr|'|t(|dr|'|j)xP|D]H}y*t r$t|t*r$|+n t,$|Wnt%k rFYnXqWYnXdS)zCreate new Popen instance.NFrYzbufsize must be an integerz0preexec_fn is not supported on Windows platformszpass_fds overriding close_fds.Tz2startupinfo is only supported on Windows platformsrz4creationflags is only supported on Windows platformszlCannot disambiguate when both text and universal_newlines are supplied but different. Pass one or the other.g?wbrq) write_throughline_bufferingrrrb)rr_devnull)-rP threadingLock _waitpid_lock_input_communication_started isinstancerJ TypeErrorrrwarningswarnRuntimeWarningrarrrpidr rrboolr _get_handlesmsvcrtZopen_osfhandlerK text_mode_sigint_wait_secs_closed_child_pipe_fdsioopen TextIOWrapper_execute_childfiltercloseOSErrorr*r`hasattrrrFrIos)rrabufsize executablerrr preexec_fn close_fdsrcwdenvr startupinfo creationflagsrestore_signalsstart_new_sessionpass_fdsrrrp2creadp2cwritec2preadc2pwriteerrreaderrwritefZto_closefdrrr rs                            zPopen.__init__cCs|jS)N)r)rrrr r>szPopen.universal_newlinescCst||_dS)N)rr)rrrrr rDscCs |||}|ddddS)Nz r )decodereplace)rrrrrrr _translate_newlinesHs zPopen._translate_newlinescCs|S)Nr)rrrr __enter__LszPopen.__enter__cCs|jr|j|jr |jz|jr2|jWd|tkrz|jdkrpy|j|jdWntk rnYnXd|_dS|XdS)Nr)r) rrrrKeyboardInterruptr_waitrr)rexc_typer tracebackrrr __exit__Os    zPopen.__exit__cCsT|js dS|jdkr(|d|jt|d|j|d|jdkrPtdk rPt|dS)Nzsubprocess %s is still running)source)rQ)_child_createdr rResourceWarningrSrRr`)rZ_maxsizeZ_warnrrr rOks    z Popen.__del__cCs"t|dsttjtj|_|jS)Nr)rrrdevnullO_RDWRr)rrrr _get_devnullzs zPopen._get_devnullc Cs|rZy|j|WnDtk r(Yn2tk rX}z|jtjkrFnWdd}~XYnXy|jWnDtk r|Yn2tk r}z|jtjkrnWdd}~XYnXdS)N)rwriteBrokenPipeErrorrerrnoEINVALr)rrrrrr _stdin_writes"  zPopen._stdin_writec CsT|jr|rtd|dkr|js|j|j|jgddkrd}d}|jrT||n6|jrp|j}|jn|jr|j}|j| n|dk rt |}nd}zy| |||\}}Wnht k r,|dk rt |j||}n|j}d|_y|j|dWntk r$YnXYnXWdd|_X|j ||d}||fS)a9Interact with process: Send data to stdin and close it. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional "input" argument should be data to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr). By default, all communication is in bytes, and therefore any "input" should be bytes, and the (stdout, stderr) will be bytes. If in text mode (indicated by self.text_mode), any "input" should be a string, and (stdout, stderr) will be strings decoded according to locale encoding, or by "encoding" if set. Text mode is triggered by setting any of text, encoding, errors or universal_newlines. z.Cannot send input after starting communicationNrr)rT)rrrrrcountrreadrr_time _communicaterminr_remaining_timerr)rrrrrendtimesigint_timeoutstsrrr rsD         zPopen.communicatecCs|S)zSCheck if child process has terminated. Set and return returncode attribute.)rS)rrrr rsz Popen.pollcCs|dkr dS|tSdS)z5Convenience for _communicate when computing timeouts.N)r)rrrrr rszPopen._remaining_timecCsL|dkr dS|st|krHt|j||r0d|nd|r@d|ndddS)z2Convenience for checking if a timeout has expired.Nr)r r)rrrar)rr orig_timeoutZ stdout_seqZ stderr_seqskip_check_and_raiserrr _check_timeoutszPopen._check_timeoutc Cs|dk rt|}y |j|dStk r|dk rJt|j||}n|j}d|_y|j|dWntk rzYnXYnXdS)z=Wait for child process to terminate; returns self.returncode.N)rr)rrrrrrr)rrrrrrr rs  z Popen.waitc Cs~|dkr|dkr|dkrdSd\}}d\}}d\}} |dkrtttj}|dkrtdd\}} t|}t| nh|tkrtdd\}}t|t|}}n<|tkrt | }n$t |t rt |}nt | }||}|dkr*ttj}|dkrtdd\} }t|}t| nn|tkrXtdd\}}t|t|}}n@|tkrrt | }n&t |t rt |}nt | }||}|dkrttj} | dkrdtdd\} } t| } t| n~|tkrtdd\}} t|t| }} nP|tkr$|} n@|tkr>t | } n&t |t rVt |} nt | } || } |||||| fS)z|Construct and return tuple with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite N)rYrYrYrYrYrY)rYrYr)rNZ GetStdHandler6Z CreatePiperFrHr*r2rZ get_osfhandlerrrJfileno_make_inheritabler7r8r+) rrrrrrrrrr_rrr rsn                        zPopen._get_handlescCs&tt|tddtj}t|S)z2Return a duplicate of handle, which is inheritablerrq)rNZDuplicateHandleZGetCurrentProcessZDUPLICATE_SAME_ACCESSrF)rhandlehrrr rZs  zPopen._make_inheritablecCstdd|DS)zFilter out console handles that can't be used in lpAttributeList["handle_list"] and make sure the list isn't empty. This also removes duplicate handles.cSs,h|]$}|d@dks$t|tjkr|qS))rNZ GetFileTypeZFILE_TYPE_CHAR).0rrrr js z,Popen._filter_handle_list..)r%)rr#rrr _filter_handle_listcszPopen._filter_handle_listc Cs|r tdt|tst|}|dkr.t}n|}d| ||fk}|rj|jtjO_| |_ ||_ ||_ |j }t |od|ko|d}|s|r|r|dkri}|_ t|dg}|d<|r|t| t|t|g7}|||dd<|r|s tdtd}| rF|jtjO_tj|_tjdd}d ||}z@t||ddt| | ||dk rtt|nd| \}}}}Wd| dkr| |dkr||dkr|t|d rt|j d |_!Xd |_"t#||_$||_%t&|dS) z$Execute program (MS Windows version)z"pass_fds not supported on Windows.NrYr#z?startupinfo.lpAttributeList['handle_list'] overriding close_fdsFZCOMSPECzcmd.exez {} /c "{}"rT)'AssertionErrorrstrrrr&rrNr:rrr r"rr%rrJrrrrr;r9r!renvironrZ CreateProcessfspathrIrrrrrrF_handlerrH)rrarrrrrrrrrrrrrrrZunused_restore_signalsZunused_start_new_sessionZuse_std_handlesZattribute_listZhave_handle_listr#ZcomspecZhpZhtrtidrrr rpsl           zPopen._execute_childcCs,|jdkr&||jd|kr&||j|_|jS)zCheck 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 )rrQZ_WaitForSingleObjectZ_WAIT_OBJECT_0Z_GetExitCodeProcessrrr rSs  zPopen._internal_pollcCs^|dkrtj}n t|d}|jdkrXt|j|}|tjkrJt|j|t |j|_|jS)z-Internal implementation of wait() on Windows.Ni) rNZINFINITErJr WaitForSingleObjectr Z WAIT_TIMEOUTrraGetExitCodeProcess)rrZtimeout_millisrrrr rs    z Popen._waitcCs|||dS)N)r`rr)rfhbufferrrr _readerthreadszPopen._readerthreadcCs\|jrBt|dsBg|_tj|j|j|jfd|_d|j_|j|j rt|dsg|_ tj|j|j |j fd|_ d|j _|j |j r| ||jdk r|j|||jrt|j||j dk r|j |||j rt|j|d}d}|jr|j}|j|j r0|j }|j |dk rB|d}|dk rT|d}||fS)N _stdout_buff)targetraT _stderr_buffr)rrrrThreadrZ stdout_threaddaemonstartrrZ stderr_threadrrrris_aliverrar)rrrrrrrrr rsF             zPopen._communicatecCsl|jdk rdS|tjkr"|nF|tjkr>t|jtjn*|tjkrZt|jtjnt d |dS)zSend a signal to the process.NzUnsupported signal: {}) r rSIGTERM terminateZ CTRL_C_EVENTrrrZCTRL_BREAK_EVENTrr)rsigrrr send_signal+s     zPopen.send_signalcCsX|jdk rdSyt|jdWn2tk rRt|j}|tjkrH||_YnXdS)zTerminates the process.Nrq)r rNZTerminateProcessr PermissionErrorr Z STILL_ACTIVE)rrcrrr r9s   zPopen.terminatec Cs,d\}}d\}}d\}} |dkr"n@|tkr8t\}}n*|tkrJ|}nt|trZ|}n|}|dkrln@|tkrt\}}n*|tkr|}nt|tr|}n|}|dkrnf|tkrt\}} nP|tkr|dkr|} n t j } n.|tkr|} nt|tr|} n|} |||||| fS)z|Construct and return tuple with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite )rYrYNrY) r*rpiper2rrrJrr+rT __stdout__) rrrrrrrrrrrrr rNsJ        c*st|ttfr|g}nt|}| rLttdr0dnd}|dg|}rL|d<dkr\|d}t\}}g}x |dkr||t |}qrWx|D]}t |qWzz|dk rg}xL| D]:\}}t |}d|krt d ||dt |qWnd}t tjr,f}ntfd d t|D}t|}||t|||tttt|||| | | |||||||||_d |_Wdt |Xt|d d}| dkr| dkr| |krt | |dkr| dkr||krt ||dkr.|dkr.||kr.t ||dk rBt |d |_t}x0t|d} || 7}| rxt|dkrPPqPWWdt |X|ry6t |jd\}!}"|!|jkr|!|"ntj"|_#Wnt$k rYnXy|%dd\}#}$}%|%&}%Wn,t k r.d}#d}$d't|}%YnXtt(|#&dt)}&t*|&t+r|$rt|$d}'|%dk}(|(rvd}%|})n|})|'dkrt,|'}%|'t-j.kr|%dt/|)7}%|&|'|%|)|&|%dS)zExecute program (POSIX version)Zgetandroidapilevelz/system/bin/shz/bin/shz-crNr=z!illegal environment variable namec3s"|]}tjt|VqdS)N)rpathrfsencode)rdir)rrr sz'Popen._execute_child..TrrYiP:rsSubprocessError0z#Bad exception data from child: {!r}asciiZnoexecrz: )0rrbytesr%rrTrrr`duprrur!rr dirnametuple get_exec_pathsetadd_posixsubprocessZ fork_execsortedmaprJrrrvr bytearrayrrwaitpid_handle_exitstatusrUr ChildProcessErrorsplitrrbuiltinsr issubclassrstrerrorrENOENTrepr)*rrarrrrrrrrrrrrrrrrrZ unix_shellZorig_executableZ errpipe_readZ errpipe_writeZlow_fds_to_closeZlow_fdZenv_listkrfZexecutable_listZ fds_to_keepZ devnull_fdZ errpipe_datapartrrZexception_nameZ hex_errnoZerr_msgZchild_exception_typeZ errno_numZchild_exec_never_calledZ err_filenamer)rr rs                                 cCsL||r|| |_n2||r*|||_n||r@|| |_ntddS)z:All callers to this function MUST hold self._waitpid_lock.zUnknown child exit status!N)r r)rrZ _WIFSIGNALEDZ _WTERMSIGZ _WIFEXITEDZ _WEXITSTATUSZ _WIFSTOPPEDZ _WSTOPSIGrrr r4s zPopen._handle_exitstatusc Cs|jdkr|jdsdSzy8|jdk r.|jS||j|\}}||jkrR||WnBtk r}z$|dk rv||_n|j|krd|_Wdd}~XYnXWd|jX|jS)zCheck 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 racquirerr4rrrelease)rrQZ_waitpidZ_WNOHANGZ_ECHILDrrerrr rS%s      cCs>yt|j|\}}Wntk r4|j}d}YnX||fS)z:All callers to this function MUST hold self._waitpid_lock.r)rr3rr5)rZ wait_flagsrrrrr _try_waitHs  zPopen._try_waitc Cs&|jdk r|jS|dk rt|}d}x|jdrzL|jdk rBP|tj\}}||jksh|dksht||jkr~| |PWd|j X| |}|dkrt |j |t|d|d}t|q(WnTxR|jdkr|j6|jdk rP|d\}}||jkr| |WdQRXqW|jS)z+Internal implementation of wait() on POSIX.NgMb@?Frrg?)r rrr>rArWNOHANGrrr4r?rrrartimesleep)rrrdelayrrZ remainingrrr rUs:           c Cs,|jrX|jsXy|jWntk r.YnX|sXy|jWntk rVYnXd}d}|jsi|_|jr~g|j|j<|jrg|j|j<|jr|j|j}|jr|j|j}|||j rt |j }t }|jr|r| |jt j|jr|jjs| |jt j|jr6|jjs6| |jt jx^|r||}|dk r~|dkr~|j||||ddtd||} |||||x| D]\} } | j|jkr<||j|jt} y|jt| j| 7_Wn,tk r|| j| jYn*X|jt|j kr|| j| jnP| j|j|jfkrt| jd} | sz|| j| j|j| j| qWq:WWdQRX|j ||d|dk rd!|}|dk rd!|}|j"r$|dk r|#||jj$|jj%}|dk r$|#||jj$|jj%}||fS)NrT)rzN_check_timeout(..., skip_check_and_raise=True) failed to raise TimeoutExpired.i)rr)&rrflushrrZ_fileobj2outputrr _save_inputr memoryview_PopenSelectorregister selectors EVENT_WRITErG EVENT_READget_maprr RuntimeErrorselectfileobj _input_offset _PIPE_BUFrrr unregisterrrr`rrrrrr)rrrrrrZ input_viewselectorrreadykeyeventschunkrrrr r~s                (        cCsF|jrB|jdkrBd|_||_|dk rB|jrB|j|jj|jj|_dS)Nr)rrrRrencoderr)rrrrr rGs  zPopen._save_inputcCs|jdkrt|j|dS)zSend a signal to the process.N)r rrr)rrrrr rs cCs|tjdS)z/Terminate the process with SIGTERM N)rrr)rrrr rscCs|tjdS)z*Kill the process with SIGKILL N)rrSIGKILL)rrrr rsz Popen.kill)rYNNNNNTFNNNNrTFr)NN)F)N)6rrrrrrrrrrrrrTrUrrrOrrrrrrrrrrrrrNr Z WAIT_OBJECT_0r rSrrrrrrr WIFSIGNALEDWTERMSIG WIFEXITED WEXITSTATUS WIFSTOPPEDWSTOPSIGr4r3rBrZECHILDrArGrrrr r)ysl-  D H  a46" )f )ErrTplatformrrrrCrr7rrrr Exceptionrr rrrrNrr/rPrKrvrSrr(rISelectSelector__all__r4r5r6r7r8r9r:r;r<r=r>r?r@rArBrCrDrEr{rJrFrRrPr*r+r2rbrr,r-r0objectr3r1rr.r/r)rrrr *sz  %     P      ;/"DI