a Z^!Bc@sdZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddlm Z ddl Z z ddlZWneydZYn0z ddlZWneydZYn0gdZzddlZddlZdZWn.eydZddlZddlZddlZYn`0ddlmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*e+gdGd d d e,Z-Gd d d e-Z.Gd dde-Z/erGdddZ0Gddde1Z2n&e3eddZ4e5edrej6Z7nej8Z7erdZ9ddZ:n gZ9ddZ:dZ;dZddZ?dd d!d"Z@d#d$ZAdd d%d&ZBGd'd(d(eCZDddddd)d*d+ZEd,d-ZFd.d/ZGd0d1ZHd2d3ZIeIZJGd4d5d5eCZKdS)6aSubprocesses 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) monotonic)PopenPIPESTDOUTcall 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_JOB)rrrrrrrr STARTUPINFOrrrrrrrrr r!c@s eZdZdS)r N)__name__ __module__ __qualname__r&r&"/usr/lib64/python3.9/subprocess.pyr ir c@<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 NcC||_||_||_||_dSN) returncodecmdoutputstderr)selfr,r-r.r/r&r&r'__init__szCalledProcessError.__init__cCsf|jrR|jdkrRzd|jt|j fWStyNd|j|j fYS0nd|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 ValueErrorr0r&r&r'__str__ys  zCalledProcessError.__str__cC|jS)z+Alias for output attribute, to match stderrr.r5r&r&r'stdoutzCalledProcessError.stdoutcC ||_dSr+r8r0valuer&r&r'r9NN r#r$r%__doc__r1r6propertyr9setterr&r&r&r'r ls   r c@r)) rzThis exception is raised when the timeout expires while waiting for a child process. Attributes: cmd, output, stdout, stderr, timeout NcCr*r+)r-timeoutr.r/)r0r-rDr.r/r&r&r'r1r2zTimeoutExpired.__init__cCsd|j|jfS)Nz'Command '%s' timed out after %s seconds)r-rDr5r&r&r'r6s zTimeoutExpired.__str__cCr7r+r8r5r&r&r'r9zTimeoutExpired.stdoutcCr;r+r8r<r&r&r'r9r>r?r@r&r&r&r'rs  rc@s,eZdZdddddddddZddZdS)r"rNdwFlags hStdInput hStdOutput hStdError wShowWindowlpAttributeListcCs0||_||_||_||_||_|p(dgi|_dS)N handle_listrF)r0rGrHrIrJrKrLr&r&r'r1s zSTARTUPINFO.__init__cCs@|j}d|vr"t|d|d<t|j|j|j|j|j|dS)NrMrF) rLcopylistr"rGrHrIrJrK)r0Z attr_listr&r&r'rNs zSTARTUPINFO.copy)r#r$r%r1rNr&r&r&r'r"s r"c@s2eZdZdZejfddZddZddZeZ dS) HandleFcCs|jsd|_||dS)NT)closed)r0 CloseHandler&r&r'Closesz Handle.ClosecCs |jsd|_t|StddS)NTzalready closed)rQintr4r5r&r&r'Detachsz Handle.DetachcCsd|jjt|fS)Nz%s(%d)) __class__r#rTr5r&r&r'__repr__zHandle.__repr__N) r#r$r%rQ_winapirRrSrUrW__del__r&r&r&r'rPs rPZPIPE_BUFi PollSelectorcCsdSr+r&r&r&r&r'_cleanuprXr\c CsZtdur dStddD]<}|jtjd}|durzt|WqtyRYq0qdS)N _deadstate)_active_internal_pollsysmaxsizeremover4)ZinstZresr&r&r'r\s iicCs*g}tjj}|dkr&|dd||S)zgReturn a list of command-line arguments reproducing the current optimization settings in sys.flags.r-ZO)raflagsZoptimizeappend)argsr=r&r&r'"_optim_args_from_interpreter_flagss ric CsVddddddd}t}|D].\}}ttj|}|dkr |d ||q tjjrd|d n$tjjrv|d tjjr|d tj d d }tjj }ttdi}d|v}|dkr| dn|r| d|r| d|D]}|d|q|r | ddD]B}||vr||} | dur4|} 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.ZdZBZSvZbZq)ZdebugZdont_write_bytecodeZno_siteZverbose bytes_warningZquietrrez-Iz-Ez-sNZ _xoptionsdevzerror::BytesWarningzdefault::BytesWarningZdefaultz-W)-Xrl)Z faulthandlerZ tracemallocZ importtimeZ showrefcountZutf8Z oldparserTz%s=%srn) riitemsgetattrrarfrgZisolatedZignore_environmentZ no_user_siteZ warnoptionsrkrcextend) Z flag_opt_maprhZflagZoptrjZwarnoptsrkZxoptionsZdev_moder=argr&r&r'_args_from_interpreter_flagssP             rsrDcOsft|i|D}z|j|dWWdS|Yn0Wdn1sX0YdS)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"]) rtN)rwaitkill)rD popenargskwargsZpr&r&r'rUs rcOs:t|i|}|r6|d}|dur,|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"]) rhNr)rgetr )rwrxretcoder-r&r&r'rfs   rcOsTd|vrtdd|vr<|ddur<|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. r9z3stdout argument not allowed, it will be overridden.inputNuniversal_newlinesFr(T)r9rDcheck)r4ryr rr9)rDrwrxr&r&r'r ys#r c@s4eZdZdZd ddZddZeejZ ddZ dS) 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). NcCr*r+)rhr,r9r/)r0rhr,r9r/r&r&r'r1r2zCompletedProcess.__init__cCshd|jd|jg}|jdur4|d|j|jdurP|d|jdt|jd|S)Nz args={!r}zreturncode={!r}z stdout={!r}z stderr={!r}z{}({})z, ) formatrhr,r9rgr/typer#join)r0rhr&r&r'rWs    zCompletedProcess.__repr__cCs |jrt|j|j|j|jdS)z6Raise CalledProcessError if the exit code is non-zero.N)r,r rhr9r/r5r&r&r'check_returncodesz!CompletedProcess.check_returncoder?) r#r$r%rAr1rW classmethodtypes GenericAlias__class_getitem__rr&r&r&r'rs   r)r{capture_outputrDr~c Os<|dur&|ddurtdt|d<|r^|ddusF|ddurNtdt|d<t|d<t|i|}z|j||d\}}Wn`ty} z4|tr|\| _| _ n| WYd} ~ nd} ~ 0|Yn0| } |r | r t | |j ||dWdn1s"0Yt|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.r9r/z@stdout and stderr arguments may not be used with capture_output.rtr.r/)ryr4rr communicaterrv _mswindowsr9r/rupollr rhr) r{rrDr~rwrxZprocessr9r/excrzr&r&r'r s6 &r cCsg}d}ttj|D]}g}|r*|dd|vp>d|vp>| }|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. Fz z z"z\z\"r})maposfsdecoderglenrqr)ZseqresultZ needquoterrZbs_bufZcr&r&r' list2cmdlines4         rc Csnzt|ddtd}d}Wn0tyH}z|j}|j}WYd}~n d}~00|dddkrf|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)shelltextr/rNrd )r rr r.r,)r-dataZexitcodeZexr&r&r'rZs rcCs 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' rm)r)r-r&r&r'rys rc CststtdsdStjdkr dSzjtd}|jdd}t|dkrHt|d }t t t |dd }tjd kr|d kr|d krWdSWnt tt fyYn0dS)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_spawnFZdarwinTZCS_GNU_LIBC_VERSIONrm)ZmaxsplitrrZ.ZlinuxZglibc)ri)rhasattrrraZplatformZconfstrsplitrr4tuplerrTZAttributeErrorOSError)ZverZpartsZlibcZversionr&r&r'_use_posix_spawns      rc@seZdZdZdZdMddddddddd d Zd d Zeej Z e d dZ e j ddZ ddZddZddZejejfddZddZddZdNddZddZd d!ZdOd"d#ZdPd$d%Zd&d'Zer4d(d)Zd*d+Z d,d-Z!d.d/Z"de#j$e#j%e#j&fd0d1Z'd2d3Z(d4d5Z)d6d7Z*d8d9Z+d:d;Z,e,Z-n~dZ.d?d/Z"e/j0e/j1e/j2fd@dAZ3de/j4e/j5e6j7fdBd1Z'dCdDZ8dEd3Z(dFd7Z*dGdHZ9dId9Z+dJd;Z,dKdLZ-dS)QraP 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) group (POSIX only) extra_groups (POSIX only) user (POSIX only) umask (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 FrdNTrr&)usergroup extra_groupsencodingerrorsrumaskc(CsFtt|_d|_d|_|dur(d}t|ts:tdt rP|durt dn8|rh|sht dt d}| durxt d|d krt d ||_d|_d|_d|_d|_d|_||_||_|dur| durt| t|krtd ||||\}}}}}}t rN|dkrt|d }|dkr4t|d }|dkrNt|d }|pb|pb|pb| |_d |_d|_|jr|d krd}d}nd}d} |durtt dst dnPt|t!rt"durt dt"#|j$} n$t|tr|} ntd%t&|| d krt d| d}!|durtt dsBt dnt|t!rVt dg}!|D]b}"t|"t!rt"durt d|!'t"#|"j$n*t|"tr|!'|"ntd%t&|"q^|!D]}#|#d krt d|#qd}$|durhtt ds t dnFt|t!r6t(dur(t dt()|j*}$nt|trH|}$ntd|$d krht d|$z|dkrt+,|d||_|jrt+j-|jd|||d|_|dkrt+,|d||_|jrt+j-|j||d |_|dkrt+,|d||_|jrt+j-|j||d |_|.|||||| | | || |||||||| |!|$||Wnt/d|j|j|jfD](}%z |%0Wnt1yYn0qd|js:g}&|t2kr|&'||t2kr|&'||t2kr|&'|t|d!r|&'|j3|&D]F}'z*t rt|'t4r|'5n t 0|'Wnt1y4Yn0qYn0dS)"zCreate new Popen instance.NFrdzbufsize 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?rmZsetregidz>The 'group' parameter is not supported on the current platformzHThe group parameter cannot be a string on systems without the grp modulez,Group must be a string or an integer, not {}z!Group ID cannot be negative, got Z setgroupszEThe 'extra_groups' parameter is not supported on the current platformz#Groups must be a list, not a stringzIItems in extra_groups cannot be strings on systems without the grp modulez9Items in extra_groups must be a string or integer, not {}Zsetreuidz=The 'user' parameter is not supported on the current platformzGThe user parameter cannot be a string on systems without the pwd modulez#User must be a string or an integerz User ID cannot be negative, got Zwb)Z write_throughline_bufferingrrZrb)rr_devnull)6r\ threadingZLock _waitpid_lock_input_communication_started isinstancerT TypeErrorrr4warningswarnRuntimeWarningrhrr9r/pidr,rrboolr _get_handlesmsvcrtZopen_osfhandlerU text_mode_sigint_wait_secs_closed_child_pipe_fdsrrstrgrpZgetgrnamZgr_gidrrrgpwdZgetpwnamZpw_uidioopenZ TextIOWrapper_execute_childZfiltercloserrrrPrS)(r0rhZbufsize executablerr9r/ preexec_fn close_fdsrcwdenvr| startupinfo creationflagsrestore_signalsstart_new_sessionpass_fdsrrrrrrrp2creadp2cwritec2preadc2pwriteerrreaderrwritergidgidsZ extra_groupZ gid_checkuidZfZto_closefdr&r&r'r1s.                                                    zPopen.__init__cCsDd|jjd|jdt|jd}t|dkr@|ddd}|S)NziPiLz...>)rVr#r,rOrhr)r0Zobj_reprr&r&r'rWs zPopen.__repr__cCr7r+)rr5r&r&r'r|r>zPopen.universal_newlinescCst||_dSr+)rr)r0r|r&r&r'r|rEcCs |||}|ddddS)Nz rz )decodeZreplace)r0rrrr&r&r'_translate_newliness zPopen._translate_newlinescCs|Sr+r&r5r&r&r' __enter__rXzPopen.__enter__cCs|jr|j|jr |jz^|jr2|jW|tkrv|jdkrlz|j|jdWntyjYn0d|_dS|nT|tkr|jdkrz|j|jdWntyYn0d|_YdS|0dS)Nrrt) r9rr/rKeyboardInterruptr_waitrru)r0Zexc_typer=Z tracebackr&r&r'__exit__s2         zPopen.__exit__cCsT|js dS|jdur(|d|jt|d|j|d|jdurPtdurPt|dS)Nzsubprocess %s is still running)Zsourcer])_child_createdr,rZResourceWarningr`r_rg)r0Z_maxsizeZ_warnr&r&r'rZs   z Popen.__del__cCs"t|dsttjtj|_|jS)Nr)rrrZdevnullZO_RDWRrr5r&r&r' _get_devnull s zPopen._get_devnullc Cs|rZz|j|WnDty&Yn4tyX}z|jtjkrBnWYd}~n d}~00z|jWnDtyzYn4ty}z|jtjkrnWYd}~n d}~00dSr+)rwriteBrokenPipeErrorrerrnoZEINVALr)r0r{rr&r&r' _stdin_write%s"    zPopen._stdin_writec CsV|jr|rtd|dur|js|j|j|jgddkrd}d}|jrT||n6|jrp|j}|jn|jr|j}|j| n|durt |}nd}zz| |||\}}Wndt y(|durt |j||}n|j}d|_z|j|dWnty Yn0Yn0Wd|_nd|_0|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 communicationNrrrtT)rr4rr9r/Zcountrreadrru_time _communicaterminr_remaining_timerr)r0r{rDr9r/endtimesigint_timeoutstsr&r&r'r>sH         zPopen.communicatecCs|S)zSCheck if child process has terminated. Set and return returncode attribute.)r`r5r&r&r'rr:z Popen.pollcCs|dur dS|tSdS)z5Convenience for _communicate when computing timeouts.N)r)r0rr&r&r'rszPopen._remaining_timecCsL|dur dS|st|krHt|j||r0d|nd|r@d|ndddS)z2Convenience for checking if a timeout has expired.Nr(r)rrrhr)r0r orig_timeoutZ stdout_seqZ stderr_seqskip_check_and_raiser&r&r'_check_timeoutszPopen._check_timeoutc Cs|durt|}z|j|dWSty|durJt|j||}n|j}d|_z|j|dWntyxYn0Yn0dS)z=Wait for child process to terminate; returns self.returncode.Nrtr)rrrrrrr)r0rDrrr&r&r'rus    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||dur|tj|Wdn1s0Yd|_dS)NrrdT) rp contextlibZ ExitStackrZcallbackrSrrr) r0rrrrrrZ devnull_fdZstackr&r&r'_close_pipe_fdss$    ,zPopen._close_pipe_fdsc Cs~|dur|dur|durdSd\}}d\}}d\}} |durtttj}|durtdd\}} t|}t| nh|tkrtdd\}}t|t|}}n<|tkrt | }n$t |t rt |}nt | }||}|dur*ttj}|durtdd\} }t|}t| nn|tkrXtdd\}}t|t|}}n@|tkrrt | }n&t |t rt |}nt | }||}|durttj} | durdtdd\} } 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)rdrdrdrdrdrdrdrdr)rYZ GetStdHandlerZ CreatePiperPrRrr rZ get_osfhandlerrrTfileno_make_inheritablerrr) r0rr9r/rrrrrrZ_r&r&r'rsp                        zPopen._get_handlescCs&tt|tddtj}t|S)z2Return a duplicate of handle, which is inheritablerrm)rYZDuplicateHandleZGetCurrentProcessZDUPLICATE_SAME_ACCESSrP)r0handleZhr&r&r'rs  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))rYZ GetFileTypeZFILE_TYPE_CHAR).0rr&r&r'Z ,s  z,Popen._filter_handle_list..)rO)r0rMr&r&r'_filter_handle_list%szPopen._filter_handle_listc Cs8t|tr nNt|tr.| r"tdt|g}n,t|tjrR| rFtdt|g}nt|}|durlt|}|dur|t}n| }d| ||fv}|r|j t j O_ | |_ ||_||_|j}t|od|vo|d}|s|r^|r^|duri}|_t|dg}|d<|r0|t| t|t|g7}|||dd<|r^|sZtdtd}| r|j t jO_ t j|_tjdd }d ||}|durt|}td ||||z@t ||ddt| | ||| \}}}}W|!| | | |||n|!| | | |||0d |_"t#||_$||_%t &|dS) z$Execute program (MS Windows version)z$bytes args is not allowed on Windows0path-like args is not allowed when shell is trueNrdrMz?startupinfo.lpAttributeList['handle_list'] overriding close_fdsFZCOMSPECzcmd.exez {} /c "{}"subprocess.PopenT)'rrbytesrrrPathLikerr"rNrGrYrrHrIrJrLrrOryrTrrrrrrrKenvironrraauditZ CreateProcessrrrP_handlerrR) r0rhrrrrrrrrrrrrrrrZunused_restore_signalsZ unused_gidZ unused_gidsZ unused_uidZ unused_umaskZunused_start_new_sessionZuse_std_handlesZattribute_listZhave_handle_listrMZcomspecZhpZhtrZtidr&r&r'r2s            zPopen._execute_childcCs,|jdur&||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)r0r^Z_WaitForSingleObjectZ_WAIT_OBJECT_0Z_GetExitCodeProcessr&r&r'r`s  zPopen._internal_pollcCs^|durtj}n t|d}|jdurXt|j|}|tjkrJt|j|t |j|_|jS)z-Internal implementation of wait() on Windows.Ni) rYZINFINITErTr,WaitForSingleObjectrZ WAIT_TIMEOUTrrhGetExitCodeProcess)r0rDZtimeout_millisrr&r&r'rs    z Popen._waitcCs|||dSr+)rgrr)r0ZfhZbufferr&r&r' _readerthreadszPopen._readerthreadcCs\|jrBt|dsBg|_tj|j|j|jfd|_d|j_|j|j rt|dsg|_ tj|j|j |j fd|_ d|j _|j |j r| ||jdur|j|||jrt|j||j dur|j |||j rt|j|d}d}|jr|j}|j|j r0|j }|j |durB|d}|durT|d}||fS)N _stdout_buff)ZtargetrhT _stderr_buffr)r9rrrZThreadrZ stdout_threadZdaemonZstartr/rZ stderr_threadrrrrZis_aliverrhr)r0r{rrr9r/r&r&r'rsN               zPopen._communicatecCsl|jdurdS|tjkr"|nF|tjkr>t|jtjn*|tjkrZt|jtjnt d |dS)Send a signal to the process.NzUnsupported signal: {}) r,r3SIGTERM terminateZ CTRL_C_EVENTrrvrZCTRL_BREAK_EVENTr4rr0Zsigr&r&r' send_signals     zPopen.send_signalcCsV|jdurdSzt|jdWn0tyPt|j}|tjkrF||_Yn0dS)zTerminates the process.Nrm)r,rYZTerminateProcessrZPermissionErrorrZ STILL_ACTIVE)r0Zrcr&r&r'r s    zPopen.terminatec Cs,d\}}d\}}d\}} |dur"n@|tkr8t\}}n*|tkrJ|}nt|trZ|}n|}|durln@|tkrt\}}n*|tkr|}nt|tr|}n|}|durnf|tkrt\}} nP|tkr|dkr|} n t j } n.|tkr|} nt|tr|} n|} |||||| fS)rrNrd) rrpiper rrrTrrraZ __stdout__) r0rr9r/rrrrrrr&r&r'rsL        c Cs|durtj}i} |rJg} dD]"} tt| d}|dur| |q| | d<g}||| fD]}|dkrX|tj|fqX|df|df| dffD]"\}}|dkr|tj||fq|r|| d<tj|||fi| |_d |_ | ||||| | dS) z'Execute program using os.posix_spawn().N)ZSIGPIPEZSIGXFZZSIGXFSZZ setsigdefrdrrmr file_actionsT) rrrpr3rgZPOSIX_SPAWN_CLOSEZPOSIX_SPAWN_DUP2rrrr)r0rhrrrrrrrrrrxZsigsetZsignameZsignumrrZfd2r&r&r' _posix_spawnTs8   zPopen._posix_spawnc-st|ttfr|g}n(t|tjr6| r.td|g}nt|}| rlttdrPdnd}|dg|}rl|d<dur||dt d|||t rFtj rF|durF|sF|sF|durF| d ks| d krF|d ks|d krF|d ks|d krF|sF|durF|durF|durF|dkrF| |||| | | ||| dS}t\}}g}|d kr|||t|}qZ|D]}t|qzhz|durg}|D]>\}}t|}d |vrtd ||d t|qnd}ttj rf} ntfddt|D} t|}!|!|t|| |tttt|!||| | | |||||||||||||_d|_Wt|n t|0| | | | |||t!}"t"|d}#|"|#7}"|#rt#|"dkrqqWt|n t|0|"rz6t$|jd\}$}%|$|jkr<|%|%ntj&|_'Wnt(yZYn0z|")dd \}&}'}(|(*}(Wn*tyd}&d}'d+t|"}(Yn0t,t-|&*dt.})t/|)t0r|'rt|'d}*|(dk}+|+rd}(|},n|},|*dkrt1|*}(|)|*|(|,|)|(dS)zExecute program (POSIX version)rZgetandroidapilevelz/system/bin/shz/bin/shz-crNrrdrrs=z!illegal environment variable namec3s"|]}tjt|VqdSr+)rpathrfsencode)rZdirrr&r'Z sz'Popen._execute_child..TiPs:sSubprocessErrors0z#Bad exception data from child: {!r}ZasciiiZnoexecr})2rrrrrrrOrrar_USE_POSIX_SPAWNrZdirnamerrrgZduprrorr4rZ get_exec_pathZsetZadd_posixsubprocessZ fork_execZsortedrrTrrrZ bytearrayrrwaitpid_handle_exitstatusrbr,ChildProcessErrorrrrrpbuiltinsr Z issubclassrZstrerror)-r0rhrrrrrrrrrrrrrrrrrrrrrZ unix_shellZorig_executableZ errpipe_readZ errpipe_writeZlow_fds_to_closeZlow_fdZenv_listZkrjZexecutable_listZ fds_to_keepZ errpipe_dataZpartrrZexception_nameZ hex_errnoZerr_msgZchild_exception_typeZ errno_numZchild_exec_never_calledZ err_filenamer&r r'r{s                                 cCs$||r|| |_n |||_dS):All callers to this function MUST hold self._waitpid_lock.N)r,)r0rwaitstatus_to_exitcodeZ _WIFSTOPPEDZ _WSTOPSIGr&r&r'r szPopen._handle_exitstatusc Cs|jdur|jdsdSzzF|jdur<|jWW|jS||j|\}}||jkr`||WnDty}z,|dur||_n|j|krd|_WYd}~n d}~00W|jn |j0|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,racquirereleaserr rr)r0r^Z_waitpidZ_WNOHANGZ_ECHILDrrZer&r&r'r`+s$      cCs<zt|j|\}}Wnty2|j}d}Yn0||fS)rr)rr rr)r0Z wait_flagsrrr&r&r' _try_waitNs   zPopen._try_waitcCsP|jdur|jS|durt|}d}|jdrzX|jdurLW|jq|tj\}}||jkr~| |W|jqW|jn |j0| |}|dkrt |j |t |d|d}t|q&nv|jdurJ|jP|jdurWdqJ|d\}}||jkr(| |Wdq1s>0Yq|jS)z+Internal implementation of wait() on POSIX.NgMb@?Frrg?)r,rrrrrrWNOHANGrr rrrhrtimeZsleep)r0rDrZdelayrrZ remainingr&r&r'r[s>             ,c Cs2|jrT|jsTz|jWnty,Yn0|sTz|jWntyRYn0d}d}|jsi|_|jrzg|j|j<|jrg|j|j<|jr|j|j}|jr|j|j}|||j rt |j }t }|jr|r| |jt j|jr|jjs| |jt j|jr2|jjs2| |jt j|r||}|durv|dkrv|j||||ddtd||} |||||| D]\} } | j|jur0||j|jt} z|jt| j| 7_Wn*ty|| j| jYn*0|jt|j kr|| j| jnP| j|j|jfvrt| jd} | sn|| j| j|j| j| qq2Wdn1s0Y|j ||d|durd!|}|durd!|}|j"r*|dur |#||jj$|jj%}|dur*|#||jj$|jj%}||fS)NrT)rzN_check_timeout(..., skip_check_and_raise=True) failed to raise TimeoutExpired.irtr()&rrZflushrrZ_fileobj2outputr9r/ _save_inputrZ memoryview_PopenSelectorZregister selectorsZ EVENT_WRITErQZ EVENT_READZget_maprrZ RuntimeErrorselectZfileobj _input_offset _PIPE_BUFrrrZ unregisterrrrgrurrrrr)r0r{rrr9r/Z input_viewZselectorrDZreadyZkeyZeventsZchunkrr&r&r'rs                    :      cCsF|jrB|jdurBd|_||_|durB|jrB|j|jj|jj|_dS)Nr)rrrrZencoderr)r0r{r&r&r'rs zPopen._save_inputcCs(||jdurdSt|j|dS)rN)rr,rrvrrr&r&r'rs cC|tjdS)z/Terminate the process with SIGTERM N)rr3rr5r&r&r'rr:cCr)z*Kill the process with SIGKILL N)rr3ZSIGKILLr5r&r&r'rvr:z Popen.kill)rdNNNNNTFNNNNrTFr&r?)Fr+):r#r$r%rArr1rWrrrrrBr|rCrrrrarbrrrZrrrrrrrurrrrrrrYrZ WAIT_OBJECT_0rr`rrrrrrvrrrZ WIFSTOPPEDZWSTOPSIGr r rrZECHILDrrr&r&r&r'rs5 j    D H  o 46'&  # )f r)LrArrrrrr3rarrrrrrrZ ImportErrorrZ__all__rrYrZModuleNotFoundErrorr rrrrrrrrrrrrrrrrrrr r!rqZ Exceptionr r rr"rTrPrprrr[rZSelectSelectorr_r\rrr rirsrrr Zobjectrr rrrrr rr&r&r&r'Z s"        P  %      ;/% EI /