U e5d1@sdZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddlm Z dddddd d d d d ddddgZ zddlZddlZdZWn0ek rdZddlZddlZddlZYnXddlmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&e 'dddddddddddd d!d"d#d$d%d&d'gGd(dde(Z)Gd)d d e)Z*Gd*dde)Z+erGd+ddZ,Gd,d-d-e-Z.n&e/ed.d/Z0e1ed0rej2Z3nej4Z3erdZ5d1d2Z6n gZ5d3d2Z6d4Z7d5Z8d6Z9d7d8Z:d9d:Z;dd;dd Z>Gd?dde?Z@ddddd@dAd ZAdBdCZBdDd ZCdEd ZDdFdGZEeEZFGdHdde?ZGdS)IaSubprocesses 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 N) monotonicPopenPIPESTDOUTcall check_callgetstatusoutput getoutput check_outputrunCalledProcessErrorDEVNULLSubprocessErrorTimeoutExpiredCompletedProcessTF)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_JOBrrrrrrrr STARTUPINFOrrrrrrrr r!r"c@s eZdZdS)rN)__name__ __module__ __qualname__r'r'"/usr/lib64/python3.8/subprocess.pyr`sc@s<eZdZdZd ddZddZeddZejd dZdS) r zRaised when run() is called with check=True and the process returns a non-zero exit status. Attributes: cmd, returncode, stdout, stderr, output NcCs||_||_||_||_dSN) returncodecmdoutputstderr)selfr*r+r,r-r'r'r(__init__jszCalledProcessError.__init__cCsh|jrT|jdkrTzd|jt|j fWStk rPd|j|j fYSXnd|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+signalZSignals ValueErrorr.r'r'r(__str__ps zCalledProcessError.__str__cCs|jS)z+Alias for output attribute, to match stderrr,r2r'r'r(stdout|szCalledProcessError.stdoutcCs ||_dSr)r4r.valuer'r'r(r5s)NN r$r%r&__doc__r/r3propertyr5setterr'r'r'r(r cs   c@s<eZdZdZd ddZddZeddZejd dZdS) rzThis exception is raised when the timeout expires while waiting for a child process. Attributes: cmd, output, stdout, stderr, timeout NcCs||_||_||_||_dSr))r+timeoutr,r-)r.r+r<r,r-r'r'r(r/szTimeoutExpired.__init__cCsd|j|jfS)Nz'Command '%s' timed out after %s seconds)r+r<r2r'r'r(r3s zTimeoutExpired.__str__cCs|jSr)r4r2r'r'r(r5szTimeoutExpired.stdoutcCs ||_dSr)r4r6r'r'r(r5s)NNr8r'r'r'r(rs  c@s,eZdZdddddddddZddZdS)r#rNdwFlags hStdInput hStdOutput hStdError wShowWindowlpAttributeListcCs0||_||_||_||_||_|p(dgi|_dS)N handle_listr=)r.r>r?r@rArBrCr'r'r(r/s zSTARTUPINFO.__init__cCs@|j}d|kr"t|d|d<t|j|j|j|j|j|dS)NrDr=) rCcopylistr#r>r?r@rArB)r.Z attr_listr'r'r(rEs zSTARTUPINFO.copy)r$r%r&r/rEr'r'r'r(r#s  c@s2eZdZdZejfddZddZddZeZ dS) HandleFcCs|jsd|_||dS)NT)closed)r. CloseHandler'r'r(Closesz Handle.ClosecCs |jsd|_t|StddS)NTzalready closed)rHintr1r2r'r'r(Detachsz Handle.DetachcCsd|jjt|fS)Nz%s(%d)) __class__r$rKr2r'r'r(__repr__szHandle.__repr__N) r$r%r&rH_winapirIrJrLrN__del__r'r'r'r(rGs rGZPIPE_BUFi PollSelectorcCsdSr)r'r'r'r'r(_cleanupsrRc Cs\tdkr dStddD]>}|jtjd}|dk rzt|Wqtk rTYqXqdS)N _deadstate)_active_internal_pollsysmaxsizeremover1)instresr'r'r(rRscCs*g}tjj}|dkr&|dd||S)zgReturn a list of command-line arguments reproducing the current optimization settings in sys.flags.r-O)rWflagsoptimizeappend)argsr7r'r'r("_optim_args_from_interpreter_flagss rec CsVddddddd}t}|D].\}}ttj|}|dkr |d ||q tjjrd|d n$tjjrv|d tjjr|d tj d d }tjj }ttdi}d|k}|dkr| dn|r| d|r| d|D]}|d|q|r | ddD]B}||kr||} | dkr4|} n d|| f} | d| fq|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)-Xrs)Z faulthandler tracemallocZ importtimeZshowalloccountZ showrefcountutf8Tz%s=%srv) reitemsgetattrrWrarcisolatedignore_environment no_user_site warnoptionsrprYextend) Z flag_opt_maprdflagoptriZwarnoptsrpZxoptionsdev_moder7argr'r'r(_args_from_interpreter_flagssP             rr<c OsLt||8}z|j|dWW5QRS|YnXW5QRXdS)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)rwaitkill)r< popenargskwargspr'r'r(rLs  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"]) rdNr)rgetr )rrretcoder+r'r'r(r]s   cOsbd|krtdd|krJ|ddkrJ|ds8|dr>d}nd}||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. r5z3stdout argument not allowed, it will be overridden.inputNuniversal_newlinestextT)r5r<check)r1rr rr5)r<rremptyr'r'r(r ps#c@s*eZdZdZd ddZddZddZdS) raEA 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||_||_||_||_dSr))rdr*r5r-)r.rdr*r5r-r'r'r(r/szCompletedProcess.__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, ) formatrdr*r5rcr-typer$join)r.rdr'r'r(rNs    zCompletedProcess.__repr__cCs |jrt|j|j|j|jdS)z6Raise CalledProcessError if the exit code is non-zero.N)r*r rdr5r-r2r'r'r(check_returncodesz!CompletedProcess.check_returncode)NN)r$r%r&r9r/rNrr'r'r'r(rs  )rcapture_outputr<rc Os |dk r&|ddk rtdt|d<|r^|ddk sF|ddk rNtdt|d<t|d<t||}z|j||d\}}Wn^tk r} z,|tr|\| _| _ n| W5d} ~ XYn|YnX| } |r| rt | |j ||dW5QRXt|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.r5r-z@stdout and stderr arguments may not be used with capture_output.rr,r-)rr1rr communicaterr _mswindowsr5r-rpollr rdr) rrr<rrrZprocessr5r-excrr'r'r(r s8  cCsg}d}ttj|D]}g}|r*|dd|kp>d|kp>| }|rN|d|D]b}|dkrj||qR|dkr|dt|dg}|dqR|r||g}||qR|r|||r|||dqd|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)maposfsdecoderclenrr)seqresultZ needquoterZbs_bufcr'r'r( list2cmdline s4         rc Cslzt|ddtd}d}Wn.tk rF}z|j}|j}W5d}~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)shellrr-rNr\ )r rr r,r*)r+dataZexitcodeZexr'r'r(rRs 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' rt)r)r+r'r'r(r qs c CststtdsdStjdkr dSzjtd}|jdd}t|dkrHt|d }t t t |dd }tjd kr|d kr|d krWdSWnt tt fk rYnXdS)aCheck if posix_spawn() can be used for subprocess. subprocess requires a posix_spawn() implementation that properly reports errors to the parent process, & sets errno on the following failures: * Process attribute actions failed. * File actions failed. * exec() failed. Prefer an implementation which can use vfork() in some cases for best performance. posix_spawnFdarwinTCS_GNU_LIBC_VERSIONrt)maxsplitrr.ZlinuxZglibc)r)rhasattrrrWplatformconfstrsplitrr1tuplerrKAttributeErrorOSError)ZverpartsZlibcversionr'r'r(_use_posix_spawn~s      rc@seZdZdZdZdKddddd d Zed d Zejd d ZddZ ddZ ddZ e j ejfddZddZddZdLddZddZddZdMd d!ZdNd"d#Zd$d%Zerd&d'Zd(d)Zd*d+Zd,d-Zdejej ej!fd.d/Z"d0d1Z#d2d3Z$d4d5Z%d6d7Z&d8d9Z'e'Z(nd:d'Zd;d<Z)d=d-Ze*j+e*j,e*j-e*j.e*j/e*j0fd>d?Z1de*j2e*j3e4j5fd@d/Z"dAdBZ6dCd1Z#dDd5Z%dEdFZ7dGd7Z&dHd9Z'dIdJZ(dS)Ora 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 Fr\NTrr')encodingerrorsrcCsltt|_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|_|jr|d krd}d}nd}z|dkrt |d||_|jrtj!|jd|||d|_|dkrt |d||_|jrtj!|j||d|_|dkr:t |d||_|jr:tj!|j||d|_|"|||||| | | || ||||||||Wnt#d|j|j|jfD]*}z |$Wnt%k rYnXq|js`g}|t&kr|'||t&kr|'||t&kr|'|t(|dr|'|j)|D]H}z*t r8t|t*r8|+n t,$|Wnt%k rZYnXqYnXdS)zCreate new Popen instance.NFr\zbufsize 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?rtwb) write_throughline_bufferingrrrb)rr_devnull)-rR threadingZLock _waitpid_lock_input_communication_started isinstancerK TypeErrorrr1warningswarnRuntimeWarningrdrr5r-pidr*rrboolr _get_handlesmsvcrtZopen_osfhandlerL text_mode_sigint_wait_secs_closed_child_pipe_fdsioopen TextIOWrapper_execute_childfiltercloserrrcrrrGrJr)r.rdbufsize executablerr5r- preexec_fn close_fdsrcwdenvr startupinfo creationflagsrestore_signalsstart_new_sessionpass_fdsrrrp2creadp2cwritec2preadc2pwriteerrreaderrwriterfZto_closefdr'r'r(r/s                          zPopen.__init__cCs|jSr))rr2r'r'r(r~szPopen.universal_newlinescCst||_dSr))rr)r.rr'r'r(rscCs |||}|ddddS)Nz r )decodereplace)r.rrrr'r'r(_translate_newliness zPopen._translate_newlinescCs|Sr)r'r2r'r'r( __enter__szPopen.__enter__cCs|jr|j|jr |jdz|jr4|jW5|tkr|jdkrrz|j|jdWntk rpYnXd|_dS|XdS)Nrr) r5rr-KeyboardInterruptr_waitrrr)r.exc_typer7 tracebackr'r'r(__exit__s    zPopen.__exit__cCsT|js dS|jdkr(|d|jt|d|j|d|jdkrPtdk rPt|dS)Nzsubprocess %s is still running)sourcerS)_child_createdr*rResourceWarningrVrUrc)r.Z_maxsizeZ_warnr'r'r(rPs   z Popen.__del__cCs"t|dsttjtj|_|jS)Nr)rrrdevnullO_RDWRrr2r'r'r( _get_devnulls zPopen._get_devnullc Cs|rZz|j|WnDtk r(Yn2tk rX}z|jtjkrFnW5d}~XYnXz|jWnDtk r|Yn2tk r}z|jtjkrnW5d}~XYnXdSr))rwriteBrokenPipeErrorrerrnoZEINVALr)r.rrr'r'r( _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}zz| |||\}}Wnht k r,|dk rt |j||}n|j}d|_z|j|dWntk r$YnXYnXW5d|_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 communicationNrTrr)rr1rr5r-countrreadrr_time _communicaterminr_remaining_timerr)r.rr<r5r-endtimesigint_timeoutstsr'r'r(rsH         zPopen.communicatecCs|S)zSCheck if child process has terminated. Set and return returncode attribute.)rVr2r'r'r(rsz Popen.pollcCs|dkr dS|tSdS)z5Convenience for _communicate when computing timeouts.N)r)r.r r'r'r(r"szPopen._remaining_timecCsL|dkr dS|st|krHt|j||r0d|nd|r@d|ndddS)z2Convenience for checking if a timeout has expired.Nrr)rrrdr)r.r  orig_timeoutZ stdout_seqZ stderr_seqskip_check_and_raiser'r'r(_check_timeout*szPopen._check_timeoutc Cs|dk rt|}z|j|dWStk r|dk rLt|j||}n|j}d|_z|j|dWntk r|YnXYnXdS)z=Wait for child process to terminate; returns self.returncode.Nrr)rrrrrrr)r.r<r r r'r'r(r6s  z Popen.waitc Cst|dd}t}trX|dkr.||j|dkrB||j|dkr||jnr|dkr~|dkr~||kr~|tj||dkr|dkr||kr|tj||dkr|dkr||kr|tj||dk r|tj|W5QRXd|_dS)Nrr\T) rz contextlib ExitStackrcallbackrJrrr) r.rrrrrrZ devnull_fdstackr'r'r(_close_pipe_fdsMs$    zPopen._close_pipe_fdsc 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)|Construct and return tuple with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite N)r\r\r\r\r\r\r\r\r)rOZ GetStdHandlerZ CreatePiperGrIrr rZ get_osfhandlerrrKfileno_make_inheritablerrr) r.rr5r-rrrrrr_r'r'r(rnst                        zPopen._get_handlescCs&tt|tddtj}t|S)z2Return a duplicate of handle, which is inheritablerrt)rOZDuplicateHandleZGetCurrentProcessZDUPLICATE_SAME_ACCESSrG)r.handlehr'r'r(rszPopen._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))rOZ GetFileTypeZFILE_TYPE_CHAR).0rr'r'r( s  z,Popen._filter_handle_list..)rF)r.rDr'r'r(_filter_handle_listszPopen._filter_handle_listcCs|r tdt|trnNt|tr:| r.tdt|g}n,t|tjr^| rRtdt|g}nt|}|dk rxt|}|dkrt }n| }d| ||fk}|r|j t j O_ | |_||_||_|j}t|od|ko|d}|s|rl|rl|dkri}|_t|dg}|d<|r>|t| t|t|g7}|||dd<|rl|shtdtd}| r|j t jO_ t j|_|stjd }|stjd d }tj|d d }tj |st!dtj |r|}n|}d"||}|dk rt|}t#$d||||z,t &||ddt| | ||| \}}}}W5|%| | | |||Xd|_'t(||_)||_*t +|dS)z$Execute program (MS Windows version)z"pass_fds not supported on Windows.z$bytes args is not allowed on Windows0path-like args is not allowed when shell is trueNr\rDz?startupinfo.lpAttributeList['handle_list'] overriding close_fdsFZComSpecZ SystemRootrZSystem32zcmd.exez:shell not found: neither %ComSpec% nor %SystemRoot% is setz {} /c "{}"subprocess.PopenT),AssertionErrorrstrbytesrrrPathLikerr#rEr>rOrr?r@rArCrrFrrKrrrrrrrBenvironpathrisabsFileNotFoundErrorrrWauditrZ CreateProcessrrG_handlerrI)r.rdrrrrrrrrrrrrrrrZunused_restore_signalsZunused_start_new_sessionZuse_std_handlesZattribute_listZhave_handle_listrDZcomspecZ system_rootZhpZhtrtidr'r'r(rs               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*)r.rTZ_WaitForSingleObjectZ_WAIT_OBJECT_0Z_GetExitCodeProcessr'r'r(rVHs  zPopen._internal_pollcCs^|dkrtj}n t|d}|jdkrXt|j|}|tjkrJt|j|t |j|_|jS)z-Internal implementation of wait() on Windows.Ni) rOZINFINITErKr*WaitForSingleObjectr*Z WAIT_TIMEOUTrrdGetExitCodeProcess)r.r<Ztimeout_millisrr'r'r(rYs    z Popen._waitcCs|||dSr))rcrr)r.Zfhbufferr'r'r( _readerthreadiszPopen._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 |r>|dnd}|rP|dnd}||fS)N _stdout_buff)targetrdT _stderr_buffr)r5rr0rZThreadr/Z stdout_threadZdaemonstartr-r2Z stderr_threadrrrrZis_aliverrdr)r.rr r r5r-r'r'r(rnsJ             zPopen._communicatecCsl|jdk rdS|tjkr"|nF|tjkr>t|jtjn*|tjkrZt|jtjnt d |dS)Send a signal to the process.NzUnsupported signal: {}) r*r0SIGTERM terminateZ CTRL_C_EVENTrrrZCTRL_BREAK_EVENTr1rr.Zsigr'r'r( send_signals     zPopen.send_signalcCsX|jdk rdSzt|jdWn2tk rRt|j}|tjkrH||_YnXdS)zTerminates the process.Nrt)r*rOZTerminateProcessr*PermissionErrorr-Z STILL_ACTIVE)r.Zrcr'r'r(r6s   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)rrNr\) rrpiper rrrKrrrW __stdout__) r.rr5r-rrrrrrr'r'r(rsP        c Cs|dkrtj}i} |rJg} dD]"} tt| d}|dk r| |q| | d<g}||| fD]}|dkrX|tj|fqX|df|df| dffD]"\}}|dkr|tj||fq|r|| d<tj|||f| |_d |_ | ||||| | dS) z'Execute program using os.posix_spawn().N)SIGPIPEZSIGXFZSIGXFSZZ setsigdefr\rrtr file_actionsT) rr%rzr0rcPOSIX_SPAWN_CLOSEPOSIX_SPAWN_DUP2rrrr)r.rdrrrrrrrrrrZsigsetZsignameZsignumr>rZfd2r'r'r( _posix_spawns<   zPopen._posix_spawnc)st|ttfr|g}n(t|tjr6| r.td|g}nt|}| rlttdrPdnd}|dg|}rl|d<dkr||dt d|||t rtj r|dkr|s|s|dkr| d ks| d kr|d ks|d kr|d ks|d kr|s| |||| | | ||| dS}t\}}g}|d krT||t|}q2|D]}t|qXzJz|dk rg}|D]>\}}t|}d |krtd ||d t|qnd}ttj rf}ntfddt|D}t|}||t|||tttt|||| | | |||||||||_d|_W5t|X| | | | |||t!}t"|d}||7}|rt#|dkrqqW5t|X|rz6t$|jd\} }!| |jkr|%|!ntj&|_'Wnt(k rYnXz|)dd \}"}#}$|$*}$Wn,tk rbd}"d}#d+t|}$YnXt,t-|"*dt.}%t/|%t0r|#rt|#d}&|$dk}'|'rd}$|}(n|}(|&dkrt1|&}$|%|&|$|(|%|$dS)zExecute program (POSIX version)rZgetandroidapilevelz/system/bin/shz/bin/shz-crNr r\rr=z!illegal environment variable namec3s"|]}tjt|VqdSr))rr&rfsencode)rdirrr'r( rsz'Popen._execute_child..TiP:sSubprocessError0z#Bad exception data from child: {!r}asciiZnoexecr)2rr"r#rr$rrFrrWr)_USE_POSIX_SPAWNr&dirnamerAr:rcduprryrCr1r get_exec_pathsetadd_posixsubprocessZ fork_execsortedrrKrrr bytearrayrrwaitpid_handle_exitstatusrXr*ChildProcessErrorrrrrzbuiltinsr issubclassrstrerror))r.rdrrrrrrrrrrrrrrrrrZ unix_shellZorig_executableZ errpipe_readZ errpipe_writeZlow_fds_to_closeZlow_fdZenv_listkriZexecutable_listZ fds_to_keepZ errpipe_datapartrr Zexception_nameZ hex_errnoerr_msgZchild_exception_typeZ errno_numZchild_exec_never_calledZ err_filenamer'rEr(r s"                              cCsL||r|| |_n2||r*|||_n||r@|| |_ntddS):All callers to this function MUST hold self._waitpid_lock.zUnknown child exit status!N)r*r)r.r Z _WIFSIGNALEDZ _WTERMSIGZ _WIFEXITEDZ _WEXITSTATUSZ _WIFSTOPPEDZ _WSTOPSIGr'r'r(rUs zPopen._handle_exitstatusc Cs|jdkr|jdsdSzz>|jdk r4|jWWpS||j|\}}||jkrX||WnBtk r}z$|dk r|||_n|j|krd|_W5d}~XYnXW5|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*racquirereleaserrUrr)r.rTZ_waitpidZ_WNOHANGZ_ECHILDrr er'r'r(rVs       cCs>zt|j|\}}Wntk r4|j}d}YnX||fS)r]r)rrTrrV)r.Z wait_flagsrr r'r'r( _try_waits  zPopen._try_waitc Cs2|jdk r|jS|dk rt|}d}|jdrzT|jdk rDWFq|tj\}}||jksj|dksjt ||jkr| |WqW5|jX| |}|dkrt |j |t|d|d}t|q&n\|jdkr,|jB|jdk rW5QRq,|d\}}||jkr | |W5QRXq|jS)z+Internal implementation of wait() on POSIX.NgMb@?Frrg?)r*rrr^r_rarWNOHANGrr!rUrrrdrtimesleep)r.r<r Zdelayrr Z remainingr'r'r(rs8             c Cs"|jrX|jsXz|jWntk r.YnX|sXz|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 j|r||}|dk rz|dkrz|j||||ddtd||} |||||| D]\} } | j|jkr6||j|jt} z|jt| j| 7_Wn,tk r || j| jYn*X|jt|j kr|| j| jnP| j|j|jfkrt| jd} | st|| j| j|j| j| qq6W5QRX|j ||d|dk rd!|}|dk rd!|}|j"r|dk r|#||jj$|jj%}|dk r|#||jj$|jj%}||fS)NrT)r zN_check_timeout(..., skip_check_and_raise=True) failed to raise TimeoutExpired.irr)&rrflushrrZ_fileobj2outputr5r- _save_inputr memoryview_PopenSelectorregister selectorsZ EVENT_WRITErHZ EVENT_READZget_maprr RuntimeErrorselectZfileobj _input_offset _PIPE_BUFrrrZ unregisterrrrcrrrrrr)r.rr r r5r-Z input_viewZselectorr<ZreadykeyZeventschunkrr'r'r(r's                  $      cCsF|jrB|jdkrBd|_||_|dk rB|jrB|j|jj|jj|_dS)Nr)rrrmrencoderr)r.rr'r'r(rfs zPopen._save_inputcCs|jdkrt|j|dS)r4N)r*rrrr7r'r'r(r8s cCs|tjdS)z/Terminate the process with SIGTERM N)r8r0r5r2r'r'r(r6scCs|tjdS)z*Kill the process with SIGKILL N)r8r0SIGKILLr2r'r'r(rsz Popen.kill)r\NNNNNTFNNNNrTFr')NN)F)N)8r$r%r&r9rr/r:rr;rrrrWrXrrrPrrrrrrrrrrrrrrOr,Z WAIT_OBJECT_0r-rVrr/rr8r6rrAr WIFSIGNALEDWTERMSIG WIFEXITED WEXITSTATUS WIFSTOPPEDWSTOPSIGrUrTrbrZECHILDrarfr'r'r'r(rs-    D H  | 26'  # )f )Hr9rWrrrrcr0rWrrrrr__all__rrOrModuleNotFoundErrorrQrlrjrrrrrrrrrrrrrrrr r!r"r Exceptionrr rr#rKrGrzrnrrQrhZSelectSelectorrUrRrrr rerrrr objectrr rrr rrKrr'r'r'r( s"  P  %      ;3" EI /