subprocess — 서브 프로세스 관리

소스 코드: Lib/subprocess.py


subprocess 모듈은 새로운 프로세스를 생성하고, 그들의 입력/출력/에러 파이프에 연결하고, 반환 코드를 얻을 수 있도록 합니다. 이 모듈은 몇 가지 이전 모듈과 함수를 대체하려고 합니다:

os.system
os.spawn*

subprocess 모듈을 사용하여 이러한 모듈과 함수를 교체하는 방법에 대한 정보는 다음 섹션에서 확인할 수 있습니다.

더 보기

PEP 324 – subprocess 모듈을 제안하는 PEP

Availability: not Emscripten, not WASI.

This module does not work or is not available on WebAssembly platforms wasm32-emscripten and wasm32-wasi. See WebAssembly platforms for more information.

subprocess 모듈 사용하기

서브 프로세스 호출에 권장되는 접근법은 처리할 수 있는 모든 사용 사례에 run() 함수를 사용하는 것입니다. 고급 사용 사례의 경우, 하부 Popen 인터페이스를 직접 사용할 수 있습니다.

subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None, **other_popen_kwargs)

args가 기술하는 명령을 실행합니다. 명령이 완료될 때까지 기다린 다음, CompletedProcess 인스턴스를 반환합니다.

위에 표시된 인자는 가장 일반적인 인자로, 아래 자주 사용되는 인자에서 설명됩니다 (따라서 약식 서명에 키워드 전용 표기법을 사용합니다). 전체 함수 서명은 Popen 생성자와 거의 같습니다 - 이 함수에 대한 대부분의 인자는 해당 인터페이스로 전달됩니다. (timeout, input, checkcapture_output은 아닙니다.)

If capture_output is true, stdout and stderr will be captured. When used, the internal Popen object is automatically created with stdout and stdin both set to PIPE. The stdout and stderr arguments may not be supplied at the same time as capture_output. If you wish to capture and combine both streams into one, set stdout to PIPE and stderr to STDOUT, instead of using capture_output.

A timeout may be specified in seconds, it is internally passed on to Popen.communicate(). If the timeout expires, the child process will be killed and waited for. The TimeoutExpired exception will be re-raised after the child process has terminated. The initial process creation itself cannot be interrupted on many platform APIs so you are not guaranteed to see a timeout exception until at least after however long process creation takes.

The input argument is passed to Popen.communicate() and thus to the subprocess’s stdin. If used it must be a byte sequence, or a string if encoding or errors is specified or text is true. When used, the internal Popen object is automatically created with stdin set to PIPE, and the stdin argument may not be used as well.

check가 참이고, 프로세스가 0이 아닌 종료 코드로 종료되면, CalledProcessError 예외가 발생합니다. 해당 예외의 어트리뷰트가 인자 및 종료 코드와 캡처되었다면 stdout과 stderr을 담습니다.

encoding이나 errors가 지정되거나, text가 참이면, stdin, stdout 및 stderr의 파일 객체는 지정된 encodingerrors 또는 io.TextIOWrapper 기본값을 사용하여 텍스트 모드로 열립니다. universal_newlines 인자는 text와 동등하고 이전 버전과의 호환성을 위해 제공됩니다. 기본적으로, 파일 객체는 바이너리 모드로 열립니다.

If env is not None, it must be a mapping that defines the environment variables for the new process; these are used instead of the default behavior of inheriting the current process’ environment. It is passed directly to Popen. This mapping can be str to str on any platform or bytes to bytes on POSIX platforms much like os.environ or os.environb.

예:

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')

버전 3.5에 추가.

버전 3.6에서 변경: encodingerrors 매개 변수를 추가했습니다

버전 3.7에서 변경: universal_newlines의 더 이해하기 쉬운 별칭으로 text 매개 변수를 추가했습니다. capture_output 매개 변수를 추가했습니다.

버전 3.12에서 변경: Changed Windows shell search order for shell=True. The current directory and %PATH% are replaced with %COMSPEC% and %SystemRoot%\System32\cmd.exe. As a result, dropping a malicious program named cmd.exe into a current directory no longer works.

class subprocess.CompletedProcess

완료된 프로세스를 나타내는, run()의 반환 값.

args

프로세스를 시작하는 데 사용된 인자. 리스트나 문자열일 수 있습니다.

returncode

자식 프로세스의 종료 상태. 일반적으로, 종료 상태 0은 성공적으로 실행되었음을 나타냅니다.

음수 값 -N은 자식이 시그널 N에 의해 종료되었음을 나타냅니다 (POSIX 전용).

stdout

자식 프로세스에서 캡처된 stdout. 바이트 시퀀스, 또는 run()이 encoding, errors, 또는 text=True로 호출되었으면 문자열. stdout이 캡처되지 않았으면 None.

stderr=subprocess.STDOUT으로 프로세스를 실행했으면, stdout과 stderr이 이 어트리뷰트에 결합하고, stderrNone이 됩니다.

stderr

자식 프로세스에서 캡처된 stderr. 바이트 시퀀스, 또는 run()이 encoding, errors, 또는 text=True로 호출되었으면 문자열. stderr이 캡처되지 않았으면 None.

check_returncode()

returncode가 0이 아니면, CalledProcessError를 발생시킵니다.

버전 3.5에 추가.

subprocess.DEVNULL

Popenstdin, stdout 또는 stderr 인자로 사용할 수 있고 특수 파일 os.devnull이 사용될 것임을 나타내는 특수 값.

버전 3.3에 추가.

subprocess.PIPE

Popenstdin, stdout 또는 stderr 인자로 사용할 수 있고 표준 스트림에 대한 파이프를 열어야 함을 나타내는 특수 값. Popen.communicate()에서 가장 유용합니다.

subprocess.STDOUT

Popenstderr 인자로 사용할 수 있고 표준 에러가 표준 출력과 같은 핸들로 가야 함을 나타내는 특수 값.

exception subprocess.SubprocessError

이 모듈의 다른 모든 예외에 대한 베이스 클래스.

버전 3.3에 추가.

exception subprocess.TimeoutExpired

자식 프로세스를 기다리는 동안 시간제한이 만료될 때 발생하는 SubprocessError의 서브 클래스.

cmd

자식 프로세스를 생성하는 데 사용된 명령.

timeout

초 단위의 시간제한.

output

Output of the child process if it was captured by run() or check_output(). Otherwise, None. This is always bytes when any output was captured regardless of the text=True setting. It may remain None instead of b'' when no output was observed.

stdout

output의 별칭, stderr과의 대칭을 위한 것입니다.

stderr

Stderr output of the child process if it was captured by run(). Otherwise, None. This is always bytes when stderr output was captured regardless of the text=True setting. It may remain None instead of b'' when no stderr output was observed.

버전 3.3에 추가.

버전 3.5에서 변경: stdoutstderr 어트리뷰트가 추가되었습니다

exception subprocess.CalledProcessError

Subclass of SubprocessError, raised when a process run by check_call(), check_output(), or run() (with check=True) returns a non-zero exit status.

returncode

자식 프로세스의 종료 상태. 시그널로 인해 프로세스가 종료되었으면, 음의 시그널 번호가 됩니다.

cmd

자식 프로세스를 생성하는 데 사용된 명령.

output

run()이나 check_output()에 의해 캡처되었다면 자식 프로세스의 출력. 그렇지 않으면, None.

stdout

output의 별칭, stderr과의 대칭을 위한 것입니다.

stderr

run()에 의해 캡처되었다면 자식 프로세스의 stderr 출력. 그렇지 않으면, None.

버전 3.5에서 변경: stdoutstderr 어트리뷰트가 추가되었습니다

자주 사용되는 인자

다양한 사용 사례를 지원하기 위해, Popen 생성자(및 편의 함수)는 많은 선택적 인자를 받아들입니다. 가장 일반적인 사용 사례에서, 이러한 인자 중 많은 부분을 기본값으로 안전하게 남겨둘 수 있습니다. 가장 흔히 필요한 인자는 다음과 같습니다:

args는 모든 호출에 필요하며 문자열 또는 프로그램 인자의 시퀀스여야 합니다. 인자의 시퀀스를 제공하는 것이 일반적으로 선호되는데, 모듈이 필요한 인자의 이스케이프와 인용을 처리하도록 하기 때문입니다 (예를 들어 파일 이름에 공백을 허용하도록). 단일 문자열을 전달하면, shellTrue(아래를 참조하십시오)이거나, 그렇지 않으면 문자열은 단순히 인자를 지정하지 않고 실행할 프로그램의 이름이어야 합니다.

stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are None, PIPE, DEVNULL, an existing file descriptor (a positive integer), and an existing file object with a valid file descriptor. With the default settings of None, no redirection will occur. PIPE indicates that a new pipe to the child should be created. DEVNULL indicates that the special file os.devnull will be used. Additionally, stderr can be STDOUT, which indicates that the stderr data from the child process should be captured into the same file handle as for stdout.

encoding이나 errors가 지정되거나, text(universal_newlines라고도 합니다)가 참이면, 파일 객체 stdin, stdoutstderr은 호출에 지정된 encodingerrors 또는 io.TextIOWrapper의 기본값을 사용하여 텍스트 모드로 열립니다.

stdin의 경우, 입력의 줄 종료 문자 '\n'이 기본 줄 구분자 os.linesep으로 변환됩니다. stdoutstderr의 경우, 출력의 모든 줄 종료가 '\n'으로 변환됩니다. 자세한 정보는 생성자에 대한 newline 인자가 None일 때에 관한 io.TextIOWrapper 클래스의 설명서를 참조하십시오.

텍스트 모드를 사용하지 않으면, stdin, stdoutstderr이 바이너리 스트림으로 열립니다. 인코딩이나 줄 종료 변환이 수행되지 않습니다.

버전 3.6에서 변경: Added the encoding and errors parameters.

버전 3.7에서 변경: text 매개 변수를 universal_newlines의 별칭으로 추가했습니다.

참고

파일 객체 Popen.stdin, Popen.stdoutPopen.stderr의 newlines 어트리뷰트는 Popen.communicate() 메서드에 의해 갱신되지 않습니다.

shellTrue이면, 지정된 명령이 셸을 통해 실행됩니다. 이것은 대부분의 시스템 셸에서 제공하는 것보다 향상된 제어 흐름을 위해 파이썬을 주로 사용하면서, 여전히 셸 파이프, 파일명 와일드카드, 환경 변수 확장 및 사용자 홈 디렉터리로의 ~ 확장과 같은 다른 셸 기능에 대한 편리한 액세스를 원할 때 유용할 수 있습니다. 그러나, 파이썬 자체가 많은 셸과 유사한 기능의 구현을 제공함에 유의하십시오 (특히, glob, fnmatch, os.walk(), os.path.expandvars(), os.path.expanduser()shutil).

버전 3.3에서 변경: universal_newlinesTrue일 때, 클래스는 locale.getpreferredencoding() 대신 인코딩 locale.getpreferredencoding(False)를 사용합니다. 이 변경에 대한 자세한 내용은 io.TextIOWrapper 클래스를 참조하십시오.

참고

shell=True를 사용하기 전에 보안 고려 사항 섹션을 읽으십시오.

이러한 옵션들은, 다른 모든 옵션과 함께, Popen 생성자 설명서에 더 자세히 설명되어 있습니다.

Popen 생성자

이 모듈에서 하부 프로세스 생성과 관리는 Popen 클래스에 의해 처리됩니다. 개발자가 편의 함수가 다루지 않는 덜 일반적인 사례를 처리할 수 있도록 큰 유연성을 제공합니다.

class subprocess.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=None, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, group=None, extra_groups=None, user=None, umask=-1, encoding=None, errors=None, text=None, pipesize=-1, process_group=None)

Execute a child program in a new process. On POSIX, the class uses os.execvpe()-like behavior to execute the child program. On Windows, the class uses the Windows CreateProcess() function. The arguments to Popen are as follows.

args는 프로그램 인자의 시퀀스이거나 그렇지 않으면 단일한 문자열이나 경로류 객체여야 합니다. 기본적으로, args가 시퀀스이면 실행할 프로그램은 args의 첫 번째 항목입니다. args가 문자열이면, 해석은 플랫폼에 따라 다르며 아래에 설명되어 있습니다. 기본 동작과의 추가 차이점에 관해서는 shellexecutable 인자를 참조하십시오. 별도의 언급이 없는 한, args를 시퀀스로 전달하는 것이 좋습니다.

경고

For maximum reliability, use a fully qualified path for the executable. To search for an unqualified name on PATH, use shutil.which(). On all platforms, passing sys.executable is the recommended way to launch the current Python interpreter again, and use the -m command-line format to launch an installed module.

Resolving the path of executable (or the first item of args) is platform dependent. For POSIX, see os.execvpe(), and note that when resolving or searching for the executable path, cwd overrides the current working directory and env can override the PATH environment variable. For Windows, see the documentation of the lpApplicationName and lpCommandLine parameters of WinAPI CreateProcess, and note that when resolving or searching for the executable path with shell=False, cwd does not override the current working directory and env cannot override the PATH environment variable. Using a full path avoids all of these variations.

시퀀스로 외부 프로그램에 어떤 인자를 전달하는 예는 다음과 같습니다:

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])

POSIX에서, args가 문자열이면, 문자열은 실행할 프로그램의 이름이나 경로로 해석됩니다. 그러나, 이것은 프로그램에 인자를 전달하지 않을 때만 수행할 수 있습니다.

참고

특히 복잡한 경우에, 셸 명령을 인자의 시퀀스로 나누는 방법이 명확하지 않을 수 있습니다. shlex.split()args의 올바른 토큰화를 결정하는 방법을 보여줄 수 있습니다:

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!

특히 셸에서 공백으로 구분된 옵션(가령 -input)과 인자(가령 eggs.txt)는 별도의 리스트 요소로 들어가지만, 셸에서 사용될 때 인용(quoting)이나 역 슬래시 이스케이프가 필요한 인자(가령 스페이스가 포함된 파일명이나 위에 표시된 echo 명령)는 단일 리스트 요소임에 유의하십시오.

윈도우에서, args가 시퀀스이면, 윈도우에서 인자 시퀀스를 문자열로 변환하기에 설명된 방식으로 문자열로 변환됩니다. 하부 CreateProcess()가 문자열에서 작동하기 때문입니다.

버전 3.6에서 변경: POSIX에서, args 매개 변수는 shellFalse이면 경로류 객체나 경로류 객체를 포함하는 시퀀스를 받아들입니다.

버전 3.8에서 변경: 윈도우에서, args 매개 변수는 shellFalse이면 경로류 객체나 바이트열과 경로류 객체를 포함하는 시퀀스를 받아들입니다.

shell 인자(기본값은 False)는 셸을 실행할 프로그램으로 사용할지를 지정합니다. shellTrue이면, args를 시퀀스가 아닌 문자열로 전달하는 것이 좋습니다.

POSIX에서 shell=True일 때, 셸의 기본값은 /bin/sh입니다. args가 문자열이면, 문자열은 셸을 통해 실행할 명령을 지정합니다. 이것은 문자열이 프롬프트에서 입력할 때와 똑같이 포맷되어야 한다는 것을 의미합니다. 예를 들어, 스페이스가 포함된 파일명을 인용하거나 역 슬래시 이스케이핑 하는 것을 포함합니다. args가 시퀀스이면, 첫 번째 항목이 명령 문자열을 지정하고, 추가 항목은 셸 자체에 대한 추가 인자로 처리됩니다. 즉, Popen은 다음과 동등한 것을 수행합니다:

Popen(['/bin/sh', '-c', args[0], args[1], ...])

윈도우에서 shell=True일 때, COMSPEC 환경 변수는 기본 셸을 지정합니다. 윈도우에서 shell=True를 지정해야 하는 유일한 경우는 실행하려는 명령이 셸에 내장되었을 때입니다 (예를 들어 dir이나 copy). 배치 파일이나 콘솔 기반 실행 파일을 실행하기 위해 shell=True가 필요하지 않습니다.

참고

shell=True를 사용하기 전에 보안 고려 사항 섹션을 읽으십시오.

bufsize는 stdin/stdout/stderr 파이프 파일 객체를 만들 때 open() 함수에 해당 인자로 제공됩니다:

  • 0 means unbuffered (read and write are one system call and can return short)

  • 1 means line buffered (only usable if text=True or universal_newlines=True)

  • 다른 양수 값은 대략 그 크기의 버퍼를 사용함을 의미합니다.

  • 음의 bufsize(기본값)는 시스템 기본값 io.DEFAULT_BUFFER_SIZE가 사용됨을 의미합니다.

버전 3.3.1에서 변경: bufsize now defaults to -1 to enable buffering by default to match the behavior that most code expects. In versions prior to Python 3.2.4 and 3.3.1 it incorrectly defaulted to 0 which was unbuffered and allowed short reads. This was unintentional and did not match the behavior of Python 2 as most code expected.

executable 인자는 실행할 대체 프로그램을 지정합니다. 거의 필요하지 않습니다. shell=False일 때, executableargs에 의해 지정된 프로그램을 대체합니다. 그러나, 원래 args는 여전히 프로그램으로 전달됩니다. 대부분의 프로그램은 args에 의해 지정된 프로그램을 명령 이름으로 취급합니다, 그래서 실제로 실행되는 프로그램과 다를 수 있습니다. POSIX에서, args 이름은 ps와 같은 유틸리티에서 실행 파일의 표시 이름이 됩니다. shell=True이면, POSIX에서 executable 인자는 기본 /bin/sh의 대체 셸을 지정합니다.

버전 3.6에서 변경: POSIX에서 executable 매개 변수는 경로류 객체를 받아들입니다.

버전 3.8에서 변경: 윈도우에서 executable 매개 변수는 바이트열과 경로류 객체를 받아들입니다.

버전 3.12에서 변경: Changed Windows shell search order for shell=True. The current directory and %PATH% are replaced with %COMSPEC% and %SystemRoot%\System32\cmd.exe. As a result, dropping a malicious program named cmd.exe into a current directory no longer works.

stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are None, PIPE, DEVNULL, an existing file descriptor (a positive integer), and an existing file object with a valid file descriptor. With the default settings of None, no redirection will occur. PIPE indicates that a new pipe to the child should be created. DEVNULL indicates that the special file os.devnull will be used. 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.

preexec_fn이 콜러블 객체로 설정되면, 이 객체는 자식 프로세스가 실행되기 직전에 자식 프로세스에서 호출됩니다. (POSIX 전용)

경고

The preexec_fn parameter is NOT SAFE to use in the presence of threads in your application. The child process could deadlock before exec is called.

참고

If you need to modify the environment for the child use the env parameter rather than doing it in a preexec_fn. The start_new_session and process_group parameters should take the place of code using preexec_fn to call os.setsid() or os.setpgid() in the child.

버전 3.8에서 변경: 서브 인터프리터에서 preexec_fn 매개 변수가 더는 지원되지 않습니다. 서브 인터프리터에서 매개 변수를 사용하면 RuntimeError가 발생합니다. 새로운 제약 사항은 mod_wsgi, uWSGI 및 기타 내장(embedded) 환경에 배치된 응용 프로그램에 영향을 줄 수 있습니다.

If close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. Otherwise when close_fds is false, file descriptors obey their inheritable flag as described in 파일 기술자의 상속.

윈도우에서, close_fds가 참이면 STARTUPINFO.lpAttributeListhandle_list 요소에 명시적으로 전달되거나 표준 핸들 리디렉션에 의하지 않는 한 자식 프로세스가 핸들을 상속하지 않습니다.

버전 3.2에서 변경: close_fds의 기본값은 False에서 위에서 설명한 것으로 변경되었습니다.

버전 3.7에서 변경: 윈도우에서 표준 핸들을 리디렉션 할 때 close_fds의 기본값이 False에서 True로 변경되었습니다. 이제 표준 핸들을 리디렉션 할 때 close_fdsTrue로 설정할 수 있습니다.

pass_fds는 부모와 자식 사이에 열려있는 파일 기술자의 선택적 시퀀스입니다. pass_fds를 제공하면 close_fdsTrue가 됩니다. (POSIX 전용)

버전 3.2에서 변경: pass_fds 매개 변수가 추가되었습니다.

If cwd is not None, the function changes the working directory to cwd before executing the child. cwd can be a string, bytes or path-like object. On POSIX, the function looks for executable (or for the first item in args) relative to cwd if the executable path is a relative path.

버전 3.6에서 변경: POSIX에서 cwd 매개 변수는 경로류 객체를 받아들입니다.

버전 3.7에서 변경: 윈도우에서 cwd 매개 변수는 경로류 객체를 받아들입니다.

버전 3.8에서 변경: 윈도우에서 cwd 매개 변수는 바이트열 객체를 받아들입니다.

restore_signals가 참(기본값)이면 파이썬이 SIG_IGN으로 설정한 모든 시그널은 실행 전에 자식 프로세스에서 SIG_DFL로 복원됩니다. 현재 여기에는 SIGPIPE, SIGXFZ 및 SIGXFSZ 시그널이 포함됩니다. (POSIX 전용)

버전 3.2에서 변경: restore_signals가 추가되었습니다.

If start_new_session is true the setsid() system call will be made in the child process prior to the execution of the subprocess.

가용성: POSIX

버전 3.2에서 변경: start_new_session이 추가되었습니다.

If process_group is a non-negative integer, the setpgid(0, value) system call will be made in the child process prior to the execution of the subprocess.

가용성: POSIX

버전 3.11에서 변경: process_group was added.

groupNone이 아니면, 서브 프로세스를 실행하기 전에 자식 프로세스에서 setregid() 시스템 호출이 수행됩니다. 제공된 값이 문자열이면, grp.getgrnam()을 통해 조회되고 gr_gid의 값이 사용됩니다. 값이 정수이면, 그대로 전달됩니다. (POSIX 전용)

가용성: POSIX

버전 3.9에 추가.

extra_groupsNone이 아니면, 서브 프로세스를 실행하기 전에 자식 프로세스에서 setgroups() 시스템 호출이 수행됩니다. extra_groups에 제공된 문자열은 grp.getgrnam()을 통해 조회되며 gr_gid의 값이 사용됩니다. 정숫값은 그대로 전달됩니다. (POSIX 전용)

가용성: POSIX

버전 3.9에 추가.

userNone이 아니면, 서브 프로세스를 실행하기 전에 자식 프로세스에서 setreuid() 시스템 호출이 수행됩니다. 제공된 값이 문자열이면, pwd.getpwnam()을 통해 조회되고 pw_uid의 값이 사용됩니다. 값이 정수이면, 그대로 전달됩니다. (POSIX 전용)

가용성: POSIX

버전 3.9에 추가.

umask가 음이 아니면, 서브 프로세스를 실행하기 전에 자식 프로세스에서 umask() 시스템 호출이 수행됩니다.

가용성: POSIX

버전 3.9에 추가.

If env is not None, it must be a mapping that defines the environment variables for the new process; these are used instead of the default behavior of inheriting the current process’ environment. This mapping can be str to str on any platform or bytes to bytes on POSIX platforms much like os.environ or os.environb.

참고

지정되면, env는 프로그램 실행에 필요한 모든 변수를 제공해야 합니다. 윈도우에서, side-by-side assembly를 실행하려면 지정된 env에 유효한 SystemRoot반드시 포함되어야 합니다.

If encoding or errors are specified, or text is true, the file objects stdin, stdout and stderr are opened in text mode with the specified encoding and errors, as described above in 자주 사용되는 인자. The universal_newlines argument is equivalent to text and is provided for backwards compatibility. By default, file objects are opened in binary mode.

버전 3.6에 추가: encodingerrors가 추가되었습니다.

버전 3.7에 추가: textuniversal_newlines의 더 가독성 있는 별칭으로 추가되었습니다.

If given, startupinfo will be a STARTUPINFO object, which is passed to the underlying CreateProcess function.

If given, creationflags, can be one or more of the following flags:

pipesize can be used to change the size of the pipe when PIPE is used for stdin, stdout or stderr. The size of the pipe is only changed on platforms that support this (only Linux at this time of writing). Other platforms will ignore this parameter.

버전 3.10에서 변경: Added the pipesize parameter.

Popen 객체는 with 문을 통해 컨텍스트 관리자로 지원됩니다; 빠져나갈 때, 표준 파일 기술자가 닫히고 프로세스를 기다립니다.

with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())

인자 executable, args, cwd, env감사 이벤트 subprocess.Popen을 발생시킵니다.

버전 3.2에서 변경: 컨텍스트 관리자 지원이 추가되었습니다.

버전 3.6에서 변경: 자식 프로세스가 여전히 실행 중이면 이제 Popen 파괴자(destructor)가 ResourceWarning 경고를 발생시킵니다.

버전 3.8에서 변경: Popen은 성능 향상을 위해 때에 따라 os.posix_spawn()을 사용할 수 있습니다. 리눅스용 윈도우 서브 시스템(Windows Subsystem for Linux)과 QEMU 사용자 에뮬레이션(QEMU User Emulation)에서, os.posix_spawn()을 사용하는 Popen 생성자는 더는 프로그램 누락과 같은 에러에 대한 예외를 발생시키지 않지만, 자식 프로세스는 0이 아닌 returncode로 실패합니다.

예외

새 프로그램이 실행을 시작하기 전에 자식 프로세스에서 발생한 예외는 부모에서 다시 발생합니다.

The most common exception raised is OSError. This occurs, for example, when trying to execute a non-existent file. Applications should prepare for OSError exceptions. Note that, when shell=True, OSError will be raised by the child only if the selected shell itself was not found. To determine if the shell failed to find the requested application, it is necessary to check the return code or output from the subprocess.

Popen이 유효하지 않은 인자로 호출되면 ValueError가 발생합니다.

호출된 프로세스가 0이 아닌 반환 코드를 반환하면 check_call()check_output()CalledProcessError를 발생시킵니다.

All of the functions and methods that accept a timeout parameter, such as run() and Popen.communicate() will raise TimeoutExpired if the timeout expires before the process exits.

이 모듈에 정의된 예외는 모두 SubprocessError를 상속합니다.

버전 3.3에 추가: SubprocessError 베이스 클래스가 추가되었습니다.

보안 고려 사항

Unlike some other popen functions, this library will not implicitly choose to call a system shell. This means that all characters, including shell metacharacters, can safely be passed to child processes. If the shell is invoked explicitly, via shell=True, it is the application’s responsibility to ensure that all whitespace and metacharacters are quoted appropriately to avoid shell injection vulnerabilities. On some platforms, it is possible to use shlex.quote() for this escaping.

On Windows, batch files (*.bat or *.cmd) may be launched by the operating system in a system shell regardless of the arguments passed to this library. This could result in arguments being parsed according to shell rules, but without any escaping added by Python. If you are intentionally launching a batch file with arguments from untrusted sources, consider passing shell=True to allow Python to escape special characters. See gh-114539 for additional discussion.

Popen 객체

Popen 클래스의 인스턴스에는 다음과 같은 메서드가 있습니다:

Popen.poll()

자식 프로세스가 종료되었는지 확인합니다. returncode 어트리뷰트를 설정하고 반환합니다. 그렇지 않으면, None을 반환합니다.

Popen.wait(timeout=None)

자식 프로세스가 종료될 때까지 기다립니다. returncode 어트리뷰트를 설정하고 반환합니다.

timeout 초 후에 프로세스가 종료되지 않으면, TimeoutExpired 예외를 발생시킵니다. 이 예외를 잡고 다시 기다리는 것은 안전합니다.

참고

이는 stdout=PIPEstderr=PIPE를 사용하고 자식 프로세스가 파이프에 너무 많은 출력을 보내서 OS 파이프 버퍼가 더 많은 데이터를 받아들일 때까지 기다리느라 블록하면 교착 상태에 빠집니다. 파이프를 사용할 때 이를 피하려면 Popen.communicate()를 사용하십시오.

참고

When the timeout parameter is not None, then (on POSIX) the function is implemented using a busy loop (non-blocking call and short sleeps). Use the asyncio module for an asynchronous wait: see asyncio.create_subprocess_exec.

버전 3.3에서 변경: timeout이 추가되었습니다.

Popen.communicate(input=None, timeout=None)

프로세스와 상호 작용합니다: stdin에 데이터를 보냅니다. 파일 끝에 도달할 때까지 stdout과 stderr에서 데이터를 읽습니다. 프로세스가 종료될 때까지 기다리고, returncode 어트리뷰트를 설정합니다. 선택적 input 인자는 자식 프로세스로 전송될 데이터이거나, 자식으로 데이터를 보내지 않으면 None이어야 합니다. 스트림이 텍스트 모드로 열렸으면, input은 문자열이어야 합니다. 그렇지 않으면, 바이트열이어야 합니다.

communicate()는 튜플 (stdout_data, stderr_data)를 반환합니다. 스트림이 텍스트 모드로 열렸으면 데이터는 문자열이 됩니다. 그렇지 않으면 바이트열입니다.

프로세스의 stdin으로 데이터를 보내려면, stdin=PIPE를 사용하여 Popen 객체를 만들어야 함에 유의하십시오. 마찬가지로, 결과 튜플에서 None 이외의 것을 얻으려면, stdout=PIPE 및/또는 stderr=PIPE도 제공해야 합니다.

timeout 초 후에 프로세스가 종료되지 않으면, TimeoutExpired 예외가 발생합니다. 이 예외를 잡고 통신을 다시 시도해도 출력이 손실되지 않습니다.

시간제한이 만료되면 자식 프로세스를 죽이지 않습니다, 올바르게 정리하려면 제대로 작동하는 응용 프로그램은 자식 프로세스를 죽이고 통신을 완료해야 합니다:

proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()

참고

읽은 데이터는 메모리에 버퍼링 되므로, 데이터 크기가 크거나 무제한이면 이 메서드를 사용하지 마십시오.

버전 3.3에서 변경: timeout이 추가되었습니다.

Popen.send_signal(signal)

시그널 signal을 자식에게 보냅니다.

프로세스가 완료되었으면 아무것도 하지 않습니다.

참고

On Windows, SIGTERM is an alias for terminate(). CTRL_C_EVENT and CTRL_BREAK_EVENT can be sent to processes started with a creationflags parameter which includes CREATE_NEW_PROCESS_GROUP.

Popen.terminate()

Stop the child. On POSIX OSs the method sends SIGTERM to the child. On Windows the Win32 API function TerminateProcess() is called to stop the child.

Popen.kill()

자식을 죽입니다. POSIX OS에서 이 함수는 SIGKILL을 자식에게 보냅니다. 윈도우에서 kill()terminate()의 별칭입니다.

The following attributes are also set by the class for you to access. Reassigning them to new values is unsupported:

Popen.args

Popen으로 전달된 args 인자 – 프로그램 인자의 시퀀스거나 단일 문자열.

버전 3.3에 추가.

Popen.stdin

If the stdin argument was PIPE, this attribute is a writeable stream object as returned by open(). If the encoding or errors arguments were specified or the text or universal_newlines argument was True, the stream is a text stream, otherwise it is a byte stream. If the stdin argument was not PIPE, this attribute is None.

Popen.stdout

If the stdout argument was PIPE, this attribute is a readable stream object as returned by open(). Reading from the stream provides output from the child process. If the encoding or errors arguments were specified or the text or universal_newlines argument was True, the stream is a text stream, otherwise it is a byte stream. If the stdout argument was not PIPE, this attribute is None.

Popen.stderr

If the stderr argument was PIPE, this attribute is a readable stream object as returned by open(). Reading from the stream provides error output from the child process. If the encoding or errors arguments were specified or the text or universal_newlines argument was True, the stream is a text stream, otherwise it is a byte stream. If the stderr argument was not PIPE, this attribute is None.

경고

다른 OS 파이프 버퍼가 차고 자식 프로세스를 블로킹하는 것으로 인한 교착 상태를 피하려면 .stdin.write, .stdout.read 또는 .stderr.read 대신 communicate()를 사용하십시오.

Popen.pid

자식 프로세스의 프로세스 ID

shell 인자를 True로 설정하면, 이것은 생성된 셸의 프로세스 ID입니다.

Popen.returncode

The child return code. Initially None, returncode is set by a call to the poll(), wait(), or communicate() methods if they detect that the process has terminated.

A None value indicates that the process hadn’t yet terminated at the time of the last method call.

음수 값 -N은 자식이 시그널 N에 의해 종료되었음을 나타냅니다 (POSIX 전용).

윈도우 Popen 도우미

STARTUPINFO 클래스와 다음 상수는 윈도우에서만 사용 가능합니다.

class subprocess.STARTUPINFO(*, dwFlags=0, hStdInput=None, hStdOutput=None, hStdError=None, wShowWindow=0, lpAttributeList=None)

윈도우 STARTUPINFO 구조체의 부분적인 지원이 Popen 생성에 사용됩니다. 다음 어트리뷰트는 키워드 전용 인자로 전달하여 설정할 수 있습니다.

버전 3.7에서 변경: 키워드 전용 인자 지원이 추가되었습니다.

dwFlags

프로세스가 창을 만들 때 특정 STARTUPINFO 어트리뷰트가 사용되는지를 결정하는 비트 필드.

si = subprocess.STARTUPINFO()
si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
hStdInput

dwFlagsSTARTF_USESTDHANDLES를 지정하면, 이 어트리뷰트는 프로세스의 표준 입력 핸들입니다. STARTF_USESTDHANDLES가 지정되지 않으면, 표준 입력의 기본값은 키보드 버퍼입니다.

hStdOutput

dwFlagsSTARTF_USESTDHANDLES를 지정하면, 이 어트리뷰트는 프로세스의 표준 출력 핸들입니다. 그렇지 않으면, 이 어트리뷰트가 무시되고 표준 출력의 기본값은 콘솔 창의 버퍼입니다.

hStdError

dwFlagsSTARTF_USESTDHANDLES를 지정하면, 이 어트리뷰트는 프로세스의 표준 에러 핸들입니다. 그렇지 않으면, 이 어트리뷰트는 무시되고 표준 에러의 기본값은 콘솔 창의 버퍼입니다.

wShowWindow

dwFlagsSTARTF_USESHOWWINDOW를 지정하면, 이 어트리뷰트는 SW_SHOWDEFAULT를 제외하고 ShowWindow 함수의 nCmdShow 매개 변수에 지정할 수 있는 값 중 어느 것이건 될 수 있습니다. 그렇지 않으면, 이 어트리뷰트는 무시됩니다.

이 어트리뷰트에 SW_HIDE가 제공됩니다. Popenshell=True와 함께 호출될 때 사용됩니다.

lpAttributeList

STARTUPINFOEX에 제공된 대로 프로세스 생성을 위한 추가 어트리뷰트 딕셔너리, UpdateProcThreadAttribute를 참조하십시오.

지원되는 어트리뷰트:

handle_list

상속될 핸들의 시퀀스. 비어 있지 않으면 close_fds는 참이어야 합니다.

Popen 생성자에 전달될 때 os.set_handle_inheritable()로 핸들을 일시적으로 상속할 수 있도록 만들어야 합니다, 그렇지 않으면 윈도우 에러 ERROR_INVALID_PARAMETER (87) 로 OSError가 발생합니다.

경고

다중 스레드 프로세스에서, 이 기능을 os.system()과 같은 모든 핸들을 상속하는 다른 프로세스 생성 함수에 대한 동시 호출과 결합할 때 상속 가능으로 표시된 핸들의 누수를 피하도록 주의하십시오. 이것은 일시적으로 상속 가능한 핸들을 만드는 표준 핸들 리디렉션에도 적용됩니다.

버전 3.7에 추가.

윈도우 상수

subprocess 모듈은 다음 상수를 노출합니다.

subprocess.STD_INPUT_HANDLE

표준 입력 장치. 처음에는, 콘솔 입력 버퍼입니다, CONIN$.

subprocess.STD_OUTPUT_HANDLE

표준 출력 장치. 처음에는, 활성 콘솔 화면 버퍼입니다, CONOUT$.

subprocess.STD_ERROR_HANDLE

표준 에러 장치. 처음에는, 활성 콘솔 화면 버퍼입니다, CONOUT$.

subprocess.SW_HIDE

창을 숨깁니다. 다른 창이 활성화됩니다.

subprocess.STARTF_USESTDHANDLES

STARTUPINFO.hStdInput, STARTUPINFO.hStdOutputSTARTUPINFO.hStdError 어트리뷰트에 추가 정보가 포함되었음을 지정합니다.

subprocess.STARTF_USESHOWWINDOW

STARTUPINFO.wShowWindow 어트리뷰트에 추가 정보가 포함되었음을 지정합니다.

subprocess.CREATE_NEW_CONSOLE

새로운 프로세스는 부모의 콘솔을 상속(기본값)하는 대신 새로운 콘솔을 갖습니다.

subprocess.CREATE_NEW_PROCESS_GROUP

새 프로세스 그룹이 만들어지도록 지정하는 Popen creationflags 매개 변수. 이 플래그는 서브 프로세스에 os.kill()을 사용하기 위해 필요합니다.

CREATE_NEW_CONSOLE이 지정되면 이 플래그는 무시됩니다.

subprocess.ABOVE_NORMAL_PRIORITY_CLASS

새 프로세스가 평균 우선순위를 초과하도록 지정하는 Popen creationflags 매개 변수.

버전 3.7에 추가.

subprocess.BELOW_NORMAL_PRIORITY_CLASS

새 프로세스가 평균 우선순위보다 낮도록 지정하는 Popen creationflags 매개 변수.

버전 3.7에 추가.

subprocess.HIGH_PRIORITY_CLASS

새 프로세스가 높은 우선순위를 갖도록 지정하는 Popen creationflags 매개 변수입니다.

버전 3.7에 추가.

subprocess.IDLE_PRIORITY_CLASS

새 프로세스가 유휴 (가장 낮은) 우선순위를 갖도록 지정하는 Popen creationflags 매개 변수.

버전 3.7에 추가.

subprocess.NORMAL_PRIORITY_CLASS

새 프로세스가 보통 우선순위를 갖도록 지정하는 Popen creationflags 매개 변수. (기본값)

버전 3.7에 추가.

subprocess.REALTIME_PRIORITY_CLASS

새 프로세스가 실시간 우선순위를 갖도록 지정하는 Popen creationflags 매개 변수. REALTIME_PRIORITY_CLASS를 사용하면 마우스 입력, 키보드 입력 및 백그라운드 디스크 플러시를 관리하는 시스템 스레드가 중단되므로 거의 사용하지 않아야 합니다. 이 클래스는 하드웨어와 직접 “대화”하거나 중단이 제한되어야 하는 짧은 작업을 수행하는 응용 프로그램에 적합할 수 있습니다.

버전 3.7에 추가.

subprocess.CREATE_NO_WINDOW

새 프로세스가 창을 만들지 않도록 지정하는 Popen creationflags 매개 변수.

버전 3.7에 추가.

subprocess.DETACHED_PROCESS

새 프로세스가 부모의 콘솔을 상속하지 않도록 지정하는 Popen creationflags 매개 변수. 이 값은 CREATE_NEW_CONSOLE과 함께 사용할 수 없습니다.

버전 3.7에 추가.

subprocess.CREATE_DEFAULT_ERROR_MODE

새 프로세스가 호출하는 프로세스의 에러 모드를 상속하지 않도록 지정하는 Popen creationflags 매개 변수. 대신, 새 프로세스는 기본 에러 모드를 갖습니다. 이 기능은 하드(hard) 에러가 비활성화된 상태로 실행되는 다중 스레드 셸 응용 프로그램에 특히 유용합니다.

버전 3.7에 추가.

subprocess.CREATE_BREAKAWAY_FROM_JOB

새 프로세스가 잡(job)과 연관되지 않도록 지정하는 Popen creationflags 매개 변수.

버전 3.7에 추가.

오래된 고수준 API

파이썬 3.5 이전에는, 이 세 가지 함수가 subprocess에 대한 고수준 API로 구성되었습니다. 이제 많은 경우에 run()을 사용할 수 있지만, 많은 기존 코드가 이러한 함수를 호출합니다.

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs)

args로 기술된 명령을 실행합니다. 명령이 완료될 때까지 기다린 후 returncode 어트리뷰트를 반환합니다.

stdout이나 stderr을 캡처해야 하는 코드는 대신 run()을 사용해야 합니다:

run(...).returncode

stdout이나 stderr을 억제하려면, DEVNULL 값을 제공하십시오.

위에 표시된 인자는 단지 몇 가지 일반적인 인자입니다. 전체 함수 서명은 Popen 생성자의 서명과 같습니다 - 이 함수는 timeout 이외의 모든 제공된 인자를 해당 인터페이스로 직접 전달합니다.

참고

이 함수에 stdout=PIPEstderr=PIPE를 사용하지 마십시오. 파이프를 읽지 않기 때문에 자식 프로세스가 OS 파이프 버퍼를 가득 채우기 충분한 출력을 생성하면 자식 프로세스가 블록 됩니다.

버전 3.3에서 변경: timeout이 추가되었습니다.

버전 3.12에서 변경: Changed Windows shell search order for shell=True. The current directory and %PATH% are replaced with %COMSPEC% and %SystemRoot%\System32\cmd.exe. As a result, dropping a malicious program named cmd.exe into a current directory no longer works.

subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs)

Run command with arguments. Wait for command to complete. If the return code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. If check_call() was unable to start the process it will propagate the exception that was raised.

stdout이나 stderr을 캡처해야 하는 코드는 대신 run()을 사용해야 합니다:

run(..., check=True)

stdout이나 stderr을 억제하려면, DEVNULL 값을 제공하십시오.

위에 표시된 인자는 단지 몇 가지 일반적인 인자입니다. 전체 함수 서명은 Popen 생성자의 서명과 같습니다 - 이 함수는 timeout 이외의 모든 제공된 인자를 해당 인터페이스로 직접 전달합니다.

참고

이 함수에 stdout=PIPEstderr=PIPE를 사용하지 마십시오. 파이프를 읽지 않기 때문에 자식 프로세스가 OS 파이프 버퍼를 가득 채우기 충분한 출력을 생성하면 자식 프로세스가 블록 됩니다.

버전 3.3에서 변경: timeout이 추가되었습니다.

버전 3.12에서 변경: Changed Windows shell search order for shell=True. The current directory and %PATH% are replaced with %COMSPEC% and %SystemRoot%\System32\cmd.exe. As a result, dropping a malicious program named cmd.exe into a current directory no longer works.

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, cwd=None, encoding=None, errors=None, universal_newlines=None, timeout=None, text=None, **other_popen_kwargs)

인자로 명령을 실행하고 출력을 반환합니다.

반환 코드가 0이 아니면 CalledProcessError 가 발생합니다. CalledProcessError 객체는 returncode 어트리뷰트에 반환 코드가 있고 output 어트리뷰트에 출력이 있습니다.

이것은 다음과 동등합니다:

run(..., check=True, stdout=PIPE).stdout

위에 표시된 인자는 단지 몇 가지 일반적인 인자입니다. 전체 함수 서명은 run()의 서명과 거의 같습니다 - 대부분의 인자는 해당 인터페이스로 직접 전달됩니다. run() 동작과 비교할 때 한가지 API 편차가 있습니다: input=None을 전달하면 부모의 표준 입력 파일 핸들을 사용하는 대신 input=b'' (또는 다른 인자에 따라 input='') 와 같게 동작합니다.

기본적으로, 이 함수는 데이터를 인코딩된 바이트열로 반환합니다. 출력 데이터의 실제 인코딩은 호출되는 명령에 따라 달라질 수 있어서, 텍스트로의 디코딩은 종종 응용 프로그램 수준에서 처리해야 합니다.

자주 사용되는 인자run()에 설명된 대로 text, encoding, errors 또는 universal_newlinesTrue로 설정하면 이 동작을 재정의할 수 있습니다.

결과에서 표준 에러도 캡처하려면 stderr=subprocess.STDOUT을 사용하십시오:

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'

버전 3.1에 추가.

버전 3.3에서 변경: timeout이 추가되었습니다.

버전 3.4에서 변경: input 키워드 인자에 대한 지원이 추가되었습니다.

버전 3.6에서 변경: encodingerrors가 추가되었습니다. 자세한 내용은 run()을 참조하십시오.

버전 3.7에 추가: textuniversal_newlines의 더 가독성 있는 별칭으로 추가되었습니다.

버전 3.12에서 변경: Changed Windows shell search order for shell=True. The current directory and %PATH% are replaced with %COMSPEC% and %SystemRoot%\System32\cmd.exe. As a result, dropping a malicious program named cmd.exe into a current directory no longer works.

이전 함수를 subprocess 모듈로 교체하기

이 섹션에서, “a는 b가 됩니다”는 b가 a의 대체로 사용될 수 있음을 의미합니다.

참고

이 섹션의 모든 “a” 함수는 실행되는 프로그램을 찾을 수 없으면 (다소간) 조용히 실패합니다; “b” 대체는 대신 OSError를 발생시킵니다.

또한, 요청된 연산이 0이 아닌 반환 코드를 생성하면 check_output()을 사용한 대체는 CalledProcessError로 실패합니다. 출력은 여전히 발생한 예외의 output 어트리뷰트로 사용 가능합니다.

다음 예에서는, 관련 함수들을 subprocess 모듈에서 이미 임포트 했다고 가정합니다.

/bin/sh 셸 명령 치환 교체하기

output=$(mycmd myarg)

는 다음처럼 됩니다:

output = check_output(["mycmd", "myarg"])

셸 파이프라인 교체하기

output=$(dmesg | grep hda)

는 다음처럼 됩니다:

p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]

p2가 p1보다 먼저 종료될 때 p1이 SIGPIPE를 수신하려면 p2를 시작한 후 p1.stdout.close() 호출이 중요합니다.

또는, 신뢰할 수 있는 입력의 경우, 셸의 자체 파이프라인 지원을 계속 사용할 수 있습니다:

output=$(dmesg | grep hda)

는 다음처럼 됩니다:

output = check_output("dmesg | grep hda", shell=True)

os.system() 교체하기

sts = os.system("mycmd" + " myarg")
# becomes
retcode = call("mycmd" + " myarg", shell=True)

노트:

  • 보통 셸을 통해 프로그램을 호출할 필요는 없습니다.

  • The call() return value is encoded differently to that of os.system().

  • The os.system() function ignores SIGINT and SIGQUIT signals while the command is running, but the caller must do this separately when using the subprocess module.

더욱 현실적인 예는 다음과 같습니다:

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)

os.spawn 패밀리 교체하기

P_NOWAIT 예:

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

P_WAIT 예:

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

벡터 예:

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

환경 예:

os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
==>
Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})

os.popen(), os.popen2(), os.popen3() 교체하기

(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
==>
p = Popen(cmd, shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdin, child_stdout) = (p.stdin, p.stdout)
(child_stdin,
 child_stdout,
 child_stderr) = os.popen3(cmd, mode, bufsize)
==>
p = Popen(cmd, shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
(child_stdin,
 child_stdout,
 child_stderr) = (p.stdin, p.stdout, p.stderr)
(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
==>
p = Popen(cmd, shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)

반환 코드 처리는 다음과 같이 번역됩니다:

pipe = os.popen(cmd, 'w')
...
rc = pipe.close()
if rc is not None and rc >> 8:
    print("There were some errors")
==>
process = Popen(cmd, stdin=PIPE)
...
process.stdin.close()
if process.wait() != 0:
    print("There were some errors")

Replacing functions from the popen2 module

참고

popen2 함수에 대한 cmd 인자가 문자열이면, 명령은 /bin/sh 를 통해 실행됩니다. 리스트면, 명령이 직접 실행됩니다.

(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
==>
p = Popen("somestring", shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)
(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
==>
p = Popen(["mycmd", "myarg"], bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)

popen2.Popen3popen2.Popen4는 다음과 같은 점을 제외하고는 기본적으로 subprocess.Popen처럼 작동합니다:

  • 실행이 실패하면 Popen은 예외를 발생시킵니다.

  • capturestderr 인자는 stderr 인자로 대체됩니다.

  • stdin=PIPEstdout=PIPE를 반드시 지정해야 합니다.

  • popen2는 기본적으로 모든 파일 기술자를 닫지만, 모든 플랫폼이나 이전 파이썬 버전에서 이 동작을 보장하려면 Popenclose_fds=True를 지정해야 합니다.

레거시 셸 호출 함수

이 모듈은 2.x commands 모듈의 다음과 같은 레거시 함수도 제공합니다. 이러한 연산은 시스템 셸을 묵시적으로 호출하고 보안과 예외 처리 일관성과 관련하여 위에서 설명한 보증 중 어느 것도 이러한 함수에 유효하지 않습니다.

subprocess.getstatusoutput(cmd, *, encoding=None, errors=None)

셸에서 cmd를 실행한 후 (exitcode, output)을 반환합니다.

Execute the string cmd in a shell with Popen.check_output() and return a 2-tuple (exitcode, output). encoding and errors are used to decode output; see the notes on 자주 사용되는 인자 for more details.

후행 줄 바꿈이 출력에서 제거됩니다. 명령의 종료 코드는 서브 프로세스의 반환 코드로 해석될 수 있습니다. 예:

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

Availability: Unix, Windows.

버전 3.3.4에서 변경: 윈도우 지원이 추가되었습니다.

이 함수는 이제 파이썬 3.3.3과 이전 버전에서와같이 (status, output) 대신 (exitcode, output) 을 반환합니다. exitcode는 returncode와 같은 값을 갖습니다.

버전 3.11에서 변경: Added the encoding and errors parameters.

subprocess.getoutput(cmd, *, encoding=None, errors=None)

셸에서 cmd를 실행한 출력(stdout과 stderr)을 반환합니다.

종료 코드를 무시하고 반환 값은 명령의 출력을 포함하는 문자열인 것을 제외하고, getstatusoutput() 과 유사합니다. 예:

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

Availability: Unix, Windows.

버전 3.3.4에서 변경: 윈도우 지원이 추가되었습니다

버전 3.11에서 변경: Added the encoding and errors parameters.

노트

윈도우에서 인자 시퀀스를 문자열로 변환하기

윈도우에서, args 시퀀스는 다음 규칙을 사용하여 구문 분석할 수 있는 문자열로 변환됩니다 (MS C 런타임에서 사용하는 규칙에 해당합니다):

  1. 인자는 스페이스나 탭인 공백으로 구분됩니다.

  2. 큰따옴표로 묶인 문자열은 포함된 공백과 관계없이 단일 인자로 해석됩니다. 인용된 문자열을 인자에 포함할 수 있습니다.

  3. 백 슬래시가 앞에 붙는 큰따옴표는 리터럴 큰따옴표로 해석됩니다.

  4. 역 슬래시는 큰따옴표 바로 앞에 오지 않는 한 문자 그대로 해석됩니다.

  5. 역 슬래시가 큰따옴표 바로 앞에 있으면, 모든 역 슬래시 쌍은 리터럴 역 슬래시로 해석됩니다. 역 슬래시 수가 홀수이면, 규칙 3에 설명된 대로 마지막 역 슬래시는 다음 큰따옴표를 이스케이프 합니다.

더 보기

shlex

명령 줄을 구문 분석하고 이스케이프 하는 함수를 제공하는 모듈.

Disabling use of vfork() or posix_spawn()

On Linux, subprocess defaults to using the vfork() system call internally when it is safe to do so rather than fork(). This greatly improves performance.

If you ever encounter a presumed highly unusual situation where you need to prevent vfork() from being used by Python, you can set the subprocess._USE_VFORK attribute to a false value.

subprocess._USE_VFORK = False  # See CPython issue gh-NNNNNN.

Setting this has no impact on use of posix_spawn() which could use vfork() internally within its libc implementation. There is a similar subprocess._USE_POSIX_SPAWN attribute if you need to prevent use of that.

subprocess._USE_POSIX_SPAWN = False  # See CPython issue gh-NNNNNN.

It is safe to set these to false on any Python version. They will have no effect on older versions when unsupported. Do not assume the attributes are available to read. Despite their names, a true value does not indicate that the corresponding function will be used, only that it may be.

Please file issues any time you have to use these private knobs with a way to reproduce the issue you were seeing. Link to that issue from a comment in your code.

버전 3.8에 추가: _USE_POSIX_SPAWN

버전 3.11에 추가: _USE_VFORK