subprocess --- ãµãããã»ã¹ç®¡ç¶
ãœãŒã¹ã³ãŒã: Lib/subprocess.py
The subprocess module allows you to spawn new processes, connect to their
input/output/error pipes, and obtain their return codes. This module intends to
replace several older modules and functions:
os.system
os.spawn*
Information about how the subprocess module can be used to replace these
modules and functions can be found in the following sections.
åè
PEP 324 -- subprocess ã¢ãžã¥ãŒã«ãææ¡ããŠãã PEP
Availability: not Android, not iOS, not WASI.
ãã®ã¢ãžã¥ãŒã«ã¯ ã¢ãã€ã«ãã©ãããã©ãŒã ãš WebAssemblyãã©ãããã©ãŒã ããµããŒãããŸããã
Using the subprocess Module¶
ãµãããã»ã¹ãèµ·åããããã«æšå¥šãããæ¹æ³ã¯ããã¹ãŠã®çšæ³ãæ±ãã 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ã³ã³ã¹ãã©ã¯ã¿ãŒã®å 容ãšåãã«ãªããŸã - ãã®é¢æ°ã®ã»ãšãã©ã®åŒæ°ã¯Popenã€ã³ã¿ãŒãã§ã€ã¹ã«æž¡ãããŸãã(timeoutãinput ããã³ check ã¯é€ãã)If capture_output is true, stdout and stderr will be captured. When used, the internal
Popenobject is automatically created with stdout and stderr both set toPIPE. 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 toPIPEand stderr toSTDOUT, 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. TheTimeoutExpiredexception 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 internalPopenobject is automatically created with stdin set toPIPE, and the stdin argument may not be used as well.check ã«çãæå®ããå Žåãããã»ã¹ãéãŒãã®çµäºã³ãŒãã§çµäºãããš
CalledProcessErroräŸå€ãéåºãããŸãã ãã®äŸå€ã®å±æ§ã«ã¯ãåŒæ°ãçµäºã³ãŒããæšæºåºåããã³æšæºãšã©ãŒåºåãææã§ããå Žåã«æ ŒçŽãããŸããencoding ãŸã㯠errors åŒæ°ãæå®ãããããtext åŒæ°ã true ã§ããå Žåãstdin, stdout ããã³ stderr ã®ããã®ãã¡ã€ã«ãªããžã§ã¯ãã¯ããã¹ãã¢ãŒãã§ãªãŒãã³ãããŸãã ãã®éã«ã¯æå®ããã encoding ããã³ errors ã䜿ãããããããã©ã«ãã®
io.TextIOWrapperã«ãªããŸããuniversal_newlines åŒæ°ã¯ text åŒæ°ãšç䟡ã§ãããåŸæ¹äºææ§ã®ããã«æäŸãããŠããŸããããã§ãªãå Žåãããã©ã«ãã§ãããã®ãã¡ã€ã«ãªããžã§ã¯ãã¯ãã€ããªã¢ãŒãã§ãªãŒãã³ãããŸããenv ã
None以å€ã®å Žåãããã¯æ°ããããã»ã¹ã§ã®ç°å¢å€æ°ãå®çŸ©ããŸããããã©ã«ãã§ã¯ãåããã»ã¹ã¯çŸåšã®ããã»ã¹ã®ç°å¢å€æ°ãåŒãç¶ããŸããPopenã«çŽæ¥æž¡ãããŸãããããããã©ãããã©ãŒã ã§os.environã®ããã«æååããæååãžããŸãPOSIX ãã©ãããã©ãŒã ã«ãããŠã¯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'')
Added in version 3.5.
ããŒãžã§ã³ 3.6 ã§å€æŽ: encoding ãš error ãåŒæ°ã«è¿œå ãããŸããã
ããŒãžã§ã³ 3.7 ã§å€æŽ: universal_newlines åŒæ°ã®ããããããããååãšããŠãtext åŒæ°ã远å ãããŸãããcapture_output åŒæ°ã远å ãããŸããã
ããŒãžã§ã³ 3.12 ã§å€æŽ:
shell=Trueã®ãšãã®Windowsã·ã§ã«æ€çŽ¢é åºã倿ŽããŸãããã«ã¬ã³ããã£ã¬ã¯ããªãš%PATH%ã¯ã%COMSPEC%ãš%SystemRoot%\System32\cmd.exeã«çœ®ãæããããŸãããããã«ãããcmd.exeãšããååã®æªæã®ããããã°ã©ã ãã«ã¬ã³ããã£ã¬ã¯ããªã«ããããããŠããåäœããªããªããŸããã
- class subprocess.CompletedProcess¶
run()ã®æ»ãå€ãããã»ã¹ãçµäºããããšã衚ããŸãã- args¶
ããã»ã¹ãèµ·åãããšãã«äœ¿çšãããåŒæ°ã1 åã®ãªã¹ãã 1 åã®æååã«ãªããŸãã
- returncode¶
åããã»ã¹ã®çµäºã³ãŒããäžè¬ã«ãçµäºã¹ããŒã¿ã¹ 0 ã¯ããã»ã¹ãæ£åžžã«çµäºããããšã瀺ããŸãã
è² ã®å€
-Nã¯åããã»ã¹ãã·ã°ãã«Nã«ããäžæ¢ãããããããšã瀺ããŸã (POSIX ã®ã¿)ã
- stdout¶
åããã»ã¹ããè£è¶³ãããæšæºåºåã§ãããã€ãåããããã¯
run()ã§ãšã³ã³ãŒãã£ã³ã°ãæå®ãããå Žåããšã©ãŒã®å Žåãtext=True ãæå®ãããå Žåã¯æååã§ããæšæºåºåãè£è¶³ã§ããªãã£ããNoneã«ãªããŸããããã»ã¹ã
stderr=subprocess.STDOUTã§å®è¡ãããå Žåãæšæºåºåãšæšæºãšã©ãŒåºåãæ··åããããã®ããã®å±æ§ã«æ ŒçŽãããstderrã¯Noneã«ãªããŸãã
- stderr¶
åããã»ã¹ããè£è¶³ãããæšæºãšã©ãŒåºåã§ãããã€ãåããããã¯
run()ã§ãšã³ã³ãŒãã£ã³ã°ãæå®ãããå Žåããšã©ãŒã®å Žåãtext=True ãæå®ãããå Žåã¯æååã§ããæšæºãšã©ãŒåºåãè£è¶³ã§ããªãã£ããNoneã«ãªããŸãã
- check_returncode()¶
returncodeãéãŒãã®å ŽåãCalledProcessErrorãéåºãããŸãã
Added in version 3.5.
- subprocess.DEVNULL¶
Popenã® stdin, stdout, stderr åŒæ°ã«æž¡ããŠãæšæºå ¥åºåãos.devnullããå ¥åºåããããã«æå®ããããã®ç¹æ®å€ã§ããAdded in version 3.3.
- subprocess.PIPE¶
Popenã® stdin, stdout, stderr åŒæ°ã«æž¡ããŠãæšæºã¹ããªãŒã ã«å¯Ÿãããã€ããéãããšãæå®ããããã®ç¹æ®å€ã§ããPopen.communicate()ã«éåžžã«æçšã§ãã
- subprocess.STDOUT¶
Popenã® stderr åŒæ°ã«æž¡ããŠãæšæºãšã©ãŒåºåãæšæºåºåãšåããã³ãã«ã«åºåãããããã«æå®ããããã®ç¹æ®å€ã§ãã
- exception subprocess.SubprocessError¶
ãã®ã¢ãžã¥ãŒã«ã®ä»ã®ãã¹ãŠã®äŸå€ã®ããã®åºåºã¯ã©ã¹ã§ãã
Added in version 3.3.
- exception subprocess.TimeoutExpired¶
SubprocessErrorã®ãµãã¯ã©ã¹ã§ããåããã»ã¹ã®çµäºãåŸ æ©ããŠããéã«ã¿ã€ã ã¢ãŠããçºçããå Žåã«éåºãããŸãã- cmd¶
åããã»ã¹ã®çæã«äœ¿çšãããã³ãã³ãæ¬æã
- timeout¶
ã¿ã€ã ã¢ãŠãç§æ°ã
- output¶
run()ã«ãŸãã¯check_output()ã«ãã£ãŠææãããå Žåã¯ãåããã»ã¹ã®åºåãšãªãããã以å€ã®å Žåã¯NoneãšãªããŸããtext=Trueã®èšå®ã«é¢ä¿ãªããåºåãææãããå Žåã¯åžžã«bytesãšãªããŸããåºåããªãå Žåã¯b''ã®ä»£ããã«``None`` ã®ãŸãŸã«ãªãããšããããŸãã
- stderr¶
run()ã«ãã£ãŠææãããå Žåãåããã»ã¹ã®æšæºãšã©ãŒåºåã衚瀺ããããã以å€ã®å Žåã¯NoneãšãªããŸããtext=Trueã®èšå®ã«é¢ä¿ãªããæšæºãšã©ãŒåºåãææããå Žåã¯åžžã«bytesãšãªããŸããæšæºãšã©ãŒåºåããªãå Žåã¯ãb''ã®ä»£ããã«Noneã®ãŸãŸã«ãªãããšããããŸãã
Added in version 3.3.
ããŒãžã§ã³ 3.5 ã§å€æŽ: 屿§ stdout ããã³ stderr ã远å ãããŸããã
- exception subprocess.CalledProcessError¶
SubprocessErrorã®ãµãã¯ã©ã¹ã§ããcheck_call()ãŸãã¯check_output()ãcheck=Trueã§ãããšãã®run()ãã«ãã£ãŠå®è¡ãããããã»ã¹ãéãŒãã®çµäºã¹ããŒã¿ã¹ãè¿ããå Žåã«éåºãããŸãã- returncode¶
Exit status of the child process, an integer. If the process exited due to a signal, this will be the negative signal number.
- cmd¶
åããã»ã¹ã®çæã«äœ¿çšãããã³ãã³ãæ¬æã
- output¶
run()ãŸãã¯check_output()ã«ãã£ãŠææãããåããã»ã¹ã®åºåãææãããªãã£ããNoneã«ãªããŸãã
- stderr¶
run()ã«ãã£ãŠææãããåããã»ã¹ã®æšæºãšã©ãŒåºåãææãããªãã£ããNoneã«ãªããŸãã
ããŒãžã§ã³ 3.5 ã§å€æŽ: 屿§ stdout ããã³ stderr ã远å ãããŸããã
ãã䜿ãããåŒæ°Â¶
å¹
åºã䜿çšäŸããµããŒãããããã«ãPopen ã³ã³ã¹ãã©ã¯ã¿ãŒ (ãšãã®ä»ã®ç°¡æé¢æ°) ã¯ãå€ãã®ãªãã·ã§ã³åŒæ°ãåãä»ããŸããäžè¬çãªçšæ³ã«ã€ããŠã¯ããããã®åŒæ°ã®å€ãã¯ããã©ã«ãå€ã®ãŸãŸã§åé¡ãããŸãããéåžžå¿
èŠãšãããåŒæ°ã¯ä»¥äžã®éãã§ã:
args ã¯ãã¹ãŠã®åŒã³åºãã«å¿ èŠã§ãæååãããã¯ããã°ã©ã åŒæ°ã®ã·ãŒã±ã³ã¹ã§ãªããã°ãªããŸãããäžè¬ã«ãåŒæ°ã®ã·ãŒã±ã³ã¹ãæž¡ãæ¹ãæãŸããã§ãããªããªããã¢ãžã¥ãŒã«ãå¿ èŠãªåŒæ°ã®ãšã¹ã±ãŒããã¯ãªãŒã (äŸãã°ãã¡ã€ã«åäžã®ã¹ããŒã¹ãèš±ãããš) ã®é¢åãèŠãããšãã§ããããã§ããåäžã®æååãæž¡ãå Žåãshell ã¯
Trueã§ãªããã°ãªããŸãã (以äžãåç §)ããããã¯ããã®æååã¯åŒæ°ãæå®ããã«å®è¡ãããåãªãããã°ã©ã ã®ååã§ãªããã°ãªããŸããã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 ofNone, no redirection will occur.PIPEindicates that a new pipe to the child should be created.DEVNULLindicates that the special fileos.devnullwill be used. Additionally, stderr can beSTDOUT, which indicates that the stderr data from the child process should be captured into the same file handle as for stdout.If encoding or errors are specified, or text (also known as universal_newlines) is true, the file objects stdin, stdout and stderr will be opened in text mode using the encoding and errors specified in the call or the defaults for
io.TextIOWrapper.stdin ã«ã€ããŠã¯ãå ¥åã§ã®è¡æ«æå
'\n'ã¯ããã©ã«ãã®è¡ã»ãã¬ãŒã¿ãŒos.linesepã«å€æãããŸããstdout ãš stderr ã«ã€ããŠã¯ãåºåã§ã®è¡æ«ã¯ãã¹ãŠ'\n'ã«å€æãããŸãã詳现ã¯io.TextIOWrapperã¯ã©ã¹ã®ããã¥ã¡ã³ãã§ã³ã³ã¹ãã©ã¯ã¿ãŒã®åŒæ° newline ãNoneã§ããå Žåãåç §ããŠãã ãããIf text mode is not used, stdin, stdout and stderr will be opened as binary streams. No encoding or line ending conversion is performed.
ããŒãžã§ã³ 3.6 ã§å€æŽ: encoding ãš errors ãåŒæ°ã«è¿œå ãããŸããã
ããŒãžã§ã³ 3.7 ã§å€æŽ: universal_newlines ã®å¥åãšããŠãtext åŒæ°ã远å ãããŸããã
泚é
ãã¡ã€ã«ãªããžã§ã¯ã
Popen.stdinãPopen.stdoutãªãã³ã«Popen.stderrã®æ¹è¡å±æ§ã¯Popen.communicate()ã¡ãœããã§æŽæ°ãããŸãããshell ã
Trueãªããæå®ãããã³ãã³ãã¯ã·ã§ã«ã«ãã£ãŠå®è¡ãããŸããããªãã Python ãäž»ãšã㊠(ã»ãšãã©ã®ã·ã¹ãã ã·ã§ã«ä»¥äžã®) 匷åãããå¶åŸ¡ãããŒã®ããã«äœ¿çšããŠããŠãããã«ã·ã§ã«ãã€ãããã¡ã€ã«åã¯ã€ã«ãã«ãŒããç°å¢å€æ°å±éã~ã®ãŠãŒã¶ãŒããŒã ãã£ã¬ã¯ããªãžã®å±éã®ãããªä»ã®ã·ã§ã«æ©èœãžã®ç°¡åãªã¢ã¯ã»ã¹ãæããªããããã¯æçšãããããŸãããããããªãããPython èªèº«ãå€ãã®ã·ã§ã«çãªæ©èœã®å®è£ ãæäŸããŠããããšã«æ³šæããŠãã ãã (ç¹ã«glob,fnmatch,os.walk(),os.path.expandvars(),os.path.expanduser(),shutil)ãããŒãžã§ã³ 3.3 ã§å€æŽ: universal_newlines ã
Trueã®å Žåãã¯ã©ã¹ã¯ãšã³ã³ãŒãã£ã³ã°locale.getpreferredencoding()ã®ä»£ããã«locale.getpreferredencoding(False)ã䜿çšããŸãããã®å€æŽã«ã€ããŠã®è©³çްã¯ãio.TextIOWrapperã¯ã©ã¹ãåç §ããŠãã ãããæ³šé
shell=Trueã䜿ãåã« ã»ãã¥ãªãã£ã§èæ ®ãã¹ãç¹ ãèªãã§ãã ããã
ãããã®ãªãã·ã§ã³ã¯ãä»ã®ãã¹ãŠã®ãªãã·ã§ã³ãšãšãã« Popen ã³ã³ã¹ãã©ã¯ã¿ãŒã®ããã¥ã¡ã³ãã®äžã§ãã詳现ã«èª¬æãããŠããŸãã
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)¶
æ°ããããã»ã¹ã§åã®ããã°ã©ã ãå®è¡ããŸããPOSIX ã«ãããŠã¯ãåã®ããã°ã©ã ãå®è¡ããããã«ããã®ã¯ã©ã¹ã¯
os.execvpe()ã®ãããªæåã䜿çšããŸããWindows ã«ãããŠã¯ããã®ã¯ã©ã¹ã¯ Windows ã®CreateProcess()颿°ã䜿çšããŸããPopenãžã®åŒæ°ã¯ä»¥äžã®éãã§ããargs ã¯ããã°ã©ã åŒæ°ã®ã·ãŒã±ã³ã¹ããåäžã®æååãŸã㯠path-like object ã§ãªããã°ãªããŸãããããã©ã«ãã§ã¯ãargs ãã·ãŒã±ã³ã¹ã®å Žåã«å®è¡ãããããã°ã©ã 㯠args ã®æåã®èŠçŽ ã§ããargs ãæååã®å Žåãè§£éã¯ãã©ãããã©ãŒã äŸåã§ãããäžèšã«èª¬æãããŸããããã©ã«ãã®æåããã®è¿œå ã®éãã«ã€ããŠã¯ shell ããã³ executable åŒæ°ãåç §ããŠãã ãããç¹ã«æèšãããªãéããargs ãã·ãŒã±ã³ã¹ãšããŠæž¡ãããšãæšå¥šãããŸãã
èŠå
For maximum reliability, use a fully qualified path for the executable. To search for an unqualified name on
PATH, useshutil.which(). On all platforms, passingsys.executableis the recommended way to launch the current Python interpreter again, and use the-mcommand-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 thePATHenvironment variable. For Windows, see the documentation of thelpApplicationNameandlpCommandLineparameters of WinAPICreateProcess, and note that when resolving or searching for the executable path withshell=False, cwd does not override the current working directory and env cannot override thePATHenvironment variable. Using a full path avoids all of these variations.An example of passing some arguments to an external program as a sequence is:
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
POSIX äžã§ã¯ãargs ãæååã®å Žåããã®æååã¯å®è¡ãã¹ãããã°ã©ã ã®ååãŸãã¯ãã¹ãšããŠè§£éãããŸããããããããã¯ããã°ã©ã ã«åŒæ°ãæž¡ããªãå Žåã«ã®ã¿å¯èœã§ãã
泚é
It may not be obvious how to break a shell command into a sequence of arguments, especially in complex cases.
shlex.split()can illustrate how to determine the correct tokenization for 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 ãªã©) ã¯ãªã¹ãã®å¥ã ã®èŠçŽ ã«ãªãã®ã«å¯Ÿããã·ã§ã«å ã§ (äžèšã®ã¹ããŒã¹ãå«ããã¡ã€ã«åã echo ã³ãã³ãã®ããã«) ã¯ã©ãŒãã£ã³ã°ãããã¯ã¹ã©ãã·ã¥ãšã¹ã±ãŒããå¿ èŠãªãã®ã¯åäžã®ãªã¹ãèŠçŽ ã§ããããšã§ãã
Windows äžã§ã¯ãargs ãã·ãŒã±ã³ã¹ãªã Windows ã«ãããåŒæ°ã·ãŒã±ã³ã¹ããæååãžã®å€æ ã«èšè¿°ãããæ¹æ³ã§æååã«å€æãããŸããããã¯æ ¹åºã®
CreateProcess()ãæååäžã§åäœããããã§ããããŒãžã§ã³ 3.6 ã§å€æŽ: args parameter accepts a path-like object if shell is
Falseand a sequence containing path-like objects on POSIX.ããŒãžã§ã³ 3.8 ã§å€æŽ: args parameter accepts a path-like object if shell is
Falseand a sequence containing bytes and path-like objects on Windows.shell åŒæ° (ããã©ã«ãã§ã¯
False) ã¯ãå®è¡ããããã°ã©ã ãšããŠã·ã§ã«ã䜿çšãããã©ãããæå®ããŸãã shell ãTrueã®å Žåã args ãã·ãŒã±ã³ã¹ãšããŠã§ã¯ãªãæååãšããŠæž¡ãããšãæšå¥šãããŸããPOSIX ã§
shell=Trueã®å Žåãã·ã§ã«ã®ããã©ã«ãã¯/bin/shã«ãªããŸããargs ãæååã®å Žåããã®æååã¯ã·ã§ã«ãä»ããŠå®è¡ãããã³ãã³ããæå®ããŸãããããã£ãŠãæååã¯å³å¯ã«ã·ã§ã«ããã³ããã§æã€åœ¢åŒãšäžèŽããªããã°ãªããŸãããäŸãã°ãæååã®äžã«ã¹ããŒã¹ãå«ããã¡ã€ã«åãããå Žåã¯ãã¯ã©ãŒãã£ã³ã°ãããã¯ã¹ã©ãã·ã¥ãšã¹ã±ãŒããå¿ èŠã§ããargs ãã·ãŒã±ã³ã¹ã®å Žåã«ã¯ãæåã®èŠçŽ ã¯ã³ãã³ãåã衚ããæååãšããŠãæ®ãã®èŠçŽ ã¯è¿œå ã®åŒæ°ãšããŠã·ã§ã«ã«æž¡ãããŸããã€ãŸãã以äžã®Popenãšç䟡ãšããããšã§ã:Popen(['/bin/sh', '-c', args[0], args[1], ...])
Windows ã§
shell=TrueãšãããšãCOMSPECç°å¢å€æ°ãããã©ã«ãã·ã§ã«ãæå®ããŸããWindows ã§shell=Trueãæå®ããå¿ èŠãããã®ã¯ãå®è¡ãããã³ãã³ããã·ã§ã«ã«çµã¿èŸŒã¿ã®å Žåã ãã§ã (äŸãã° dir ã copy)ãããããã¡ã€ã«ãã³ã³ãœãŒã«ããŒã¹ã®å®è¡ãã¡ã€ã«ãå®è¡ããããã«shell=Trueã¯å¿ èŠãããŸãããæ³šé
shell=Trueã䜿ãåã« ã»ãã¥ãªãã£ã§èæ ®ãã¹ãç¹ ãèªãã§ãã ãããbufsize ã¯æšæºå ¥å/æšæºåºå/æšæºãšã©ãŒåºåãã€ããã¡ã€ã«ãªããžã§ã¯ããçæãããšãã«
open()颿°ã®å¯Ÿå¿ããåŒæ°ã«æž¡ãããŸã:0means unbuffered (read and write are one system call and can return short)1means line buffered (only usable iftext=Trueoruniversal_newlines=True)ãã以å€ã®æ£ã®æŽæ°ã¯ãããã¡ãŒã®ãããã®ãµã€ãºã«ãªãããšãæå³ããŸãã
è² ã®ãµã€ãº (ããã©ã«ã) 㯠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
0which 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ã®ãšãã¯ãexecutable 㯠args ã§æå®ãããŠããå®è¡ããã°ã©ã ã眮æããŸãããããããªãªãžãã«ã® args ã¯äŸç¶ãšããŠããã°ã©ã ã«æž¡ãããŸããã»ãšãã©ã®ããã°ã©ã ã¯ãargs ã§æå®ãããããã°ã©ã ãã³ãã³ãåãšããŠæ±ããŸãããããŠãããã¯å®éã«å®è¡ãããããã°ã©ã ãšã¯ç°ãªãå¯èœæ§ããããŸããPOSIX ã«ãããŠãps ã®ãããªãŠãŒãã£ãªãã£ã®äžã§ã¯ãargs åãå®è¡ãã¡ã€ã«ã®è¡šç€ºåã«ãªããŸããshell=Trueã®å ŽåãPOSIX ã«ãã㊠executable åŒæ°ã¯ããã©ã«ãã®/bin/shã«å¯Ÿãã眮æã·ã§ã«ãæå®ããŸããããŒãžã§ã³ 3.6 ã§å€æŽ: executable åŒæ°ã POSIX ã§ path-like object ãåãä»ããããã«ãªããŸããã
ããŒãžã§ã³ 3.8 ã§å€æŽ: executable åŒæ°ã Windows ã§ path-like object ãåãä»ããããã«ãªããŸããã
ããŒãžã§ã³ 3.12 ã§å€æŽ:
shell=Trueã®ãšãã®Windowsã·ã§ã«æ€çŽ¢é åºã倿ŽããŸãããã«ã¬ã³ããã£ã¬ã¯ããªãš%PATH%ã¯ã%COMSPEC%ãš%SystemRoot%\System32\cmd.exeã«çœ®ãæããããŸãããããã«ãããcmd.exeãšããååã®æªæã®ããããã°ã©ã ãã«ã¬ã³ããã£ã¬ã¯ããªã«ããããããŠããåäœããªããªããŸããã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 ofNone, no redirection will occur.PIPEindicates that a new pipe to the child should be created.DEVNULLindicates that the special fileos.devnullwill be used. Additionally, stderr can beSTDOUT, which indicates that the stderr data from the applications should be captured into the same file handle as for stdout.preexec_fn ã«åŒã³åºãå¯èœãªããžã§ã¯ããæå®ãããŠããå Žåããã®ãªããžã§ã¯ãã¯åããã»ã¹ãå®è¡ãããçŽå (fork ãããããšãexec ãããçŽå) ã«åããã»ã¹å ã§åŒã°ããŸãã(POSIXã®ã¿)
èŠå
ã¢ããªã±ãŒã·ã§ã³äžã«è€æ°ã®ã¹ã¬ãããååšããç¶æ ã§ preexec_fn åŒæ°ã䜿çšããã®ã¯**å®å šã§ã¯ãããŸãã**ãexec ãåŒã°ããåã«åããã»ã¹ããããããã¯ãèµ·ããããšããããŸãã
泚é
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()oros.setpgid()in the child.ããŒãžã§ã³ 3.8 ã§å€æŽ: The preexec_fn parameter is no longer supported in subinterpreters. The use of the parameter in a subinterpreter raises
RuntimeError. The new restriction may affect applications that are deployed in mod_wsgi, uWSGI, and other embedded environments.If close_fds is true, all file descriptors except
0,1and2will be closed before the child process is executed. Otherwise when close_fds is false, file descriptors obey their inheritable flag as described in ãã¡ã€ã«èšè¿°åã®ç¶æ¿.On Windows, if close_fds is true then no handles will be inherited by the child process unless explicitly passed in the
handle_listelement ofSTARTUPINFO.lpAttributeList, or by standard handle redirection.ããŒãžã§ã³ 3.2 ã§å€æŽ: close_fds ã®ããã©ã«ãã¯ã
Falseããäžèšã®ãã®ã«å€æŽãããŸãããããŒãžã§ã³ 3.7 ã§å€æŽ: On Windows the default for close_fds was changed from
FalsetoTruewhen redirecting the standard handles. It's now possible to set close_fds toTruewhen redirecting the standard handles.pass_fds ã¯ãªãã·ã§ã³ã§ã芪ãšåã®éã§éãããŸãŸã«ããŠãããã¡ã€ã«èšè¿°åã®ã·ãŒã±ã³ã¹ãæå®ããŸããäœããã® pass_fds ãæž¡ããå Žåãclose_fds ã¯åŒ·å¶çã«
Trueã«ãªããŸãã(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 ã§å€æŽ: cwd åŒæ°ã POSIX ã§ path-like object ãåãä»ããããã«ãªããŸããã
ããŒãžã§ã³ 3.7 ã§å€æŽ: cwd åŒæ°ã Windows ã§ path-like object ãåãä»ããããã«ãªããŸããã
ããŒãžã§ã³ 3.8 ã§å€æŽ: cwd åŒæ°ã Windows ã§ bytes ãªããžã§ã¯ããåãä»ããããã«ãªããŸããã
restore_signals ãçã®å Žå (ããã©ã«ã)ãPython ã SIG_IGN ã«èšå®ãããã¹ãŠã®ã·ã°ãã«ã¯åããã»ã¹ã exec ãããåã«åããã»ã¹ã® 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.Availability: 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.Availability: POSIX
ããŒãžã§ã³ 3.11 ã§å€æŽ: process_group was added.
If group is not
None, the setregid() system call will be made in the child process prior to the execution of the subprocess. If the provided value is a string, it will be looked up viagrp.getgrnam()and the value ingr_gidwill be used. If the value is an integer, it will be passed verbatim. (POSIX only)Availability: POSIX
Added in version 3.9.
If extra_groups is not
None, the setgroups() system call will be made in the child process prior to the execution of the subprocess. Strings provided in extra_groups will be looked up viagrp.getgrnam()and the values ingr_gidwill be used. Integer values will be passed verbatim. (POSIX only)Availability: POSIX
Added in version 3.9.
If user is not
None, the setreuid() system call will be made in the child process prior to the execution of the subprocess. If the provided value is a string, it will be looked up viapwd.getpwnam()and the value inpw_uidwill be used. If the value is an integer, it will be passed verbatim. (POSIX only)泚é
Specifying user will not drop existing supplementary group memberships! The caller must also pass
extra_groups=()to reduce the group membership of the child process for security purposes.Availability: POSIX
Added in version 3.9.
If umask is not negative, the umask() system call will be made in the child process prior to the execution of the subprocess.
Availability: POSIX
Added in version 3.9.
env ã
None以å€ã®å Žåãããã¯æ°ããããã»ã¹ã§ã®ç°å¢å€æ°ãå®çŸ©ããŸããããã©ã«ãã§ã¯ãåããã»ã¹ã¯çŸåšã®ããã»ã¹ã®ç°å¢å€æ°ãåŒãç¶ããŸãããããããã©ãããã©ãŒã ã§os.environã®ããã«æååããæååãžããŸãPOSIX ãã©ãããã©ãŒã ã«ãããŠã¯os.environbã®ããã«ãã€ããããã€ããžããå®çŸ©ããããšåºæ¥ãŸããæ³šé
If specified, env must provide any variables required for the program to execute. On Windows, in order to run a side-by-side assembly the specified env must include a valid
%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.
Added in version 3.6: encoding ãš errors ã远å ãããŸããã
Added in version 3.7: text ããuniversal_newlines ã®ããèªã¿ãããå¥åãšããŠè¿œå ãããŸããã
If given, startupinfo will be a
STARTUPINFOobject, which is passed to the underlyingCreateProcessfunction.If given, creationflags, can be one or more of the following flags:
pipesize can be used to change the size of the pipe when
PIPEis 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())
Popen and the other functions in this module that use it raise an auditing event
subprocess.Popenwith argumentsexecutable,args,cwd, andenv. The value forargsmay be a single string or a list of strings, depending on platform.ããŒãžã§ã³ 3.2 ã§å€æŽ: ã³ã³ããã¹ããããŒãžã£ãŒãµããŒãã远å ãããŸããã
ããŒãžã§ã³ 3.6 ã§å€æŽ: Popen destructor now emits a
ResourceWarningwarning if the child process is still running.ããŒãžã§ã³ 3.8 ã§å€æŽ: Popen can use
os.posix_spawn()in some cases for better performance. On Windows Subsystem for Linux and QEMU User Emulation, Popen constructor usingos.posix_spawn()no longer raise an exception on errors like missing program, but the child process fails with a non-zeroreturncode.
äŸå€Â¶
Exceptions raised in the child process, before the new program has started to execute, will be re-raised in the parent.
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 ãçºçããŸãã
åŒã³åºãããããã»ã¹ãéãŒãã®ãªã¿ãŒã³ã³ãŒããè¿ããå Žå 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 ãç¶æ¿ããŠããŸãã
Added in version 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äŸå€ãéåºããŸãããã®äŸå€ãææã㊠wait ãå詊è¡ããã®ã¯å®å šã§ããæ³šé
stdout=PIPEãstderr=PIPEã䜿ã£ãŠããŠãããå€ãã®ããŒã¿ãåãå ¥ããããã« OS ã®ãã€ããããã¡ãŒããããã¯ããŠãããã€ãã«åããã»ã¹ãååãªåºåãçæããå Žåããããããã¯ãçºçããŸãããããé¿ããã«ã¯Popen.communicate()ã䜿çšããŠãã ãããæ³šé
When the
timeoutparameter is notNone, then (on POSIX) the function is implemented using a busy loop (non-blocking call and short sleeps). Use theasynciomodule for an asynchronous wait: seeasyncio.create_subprocess_exec.ããŒãžã§ã³ 3.3 ã§å€æŽ: timeout ã远å ãããŸãã
- Popen.communicate(input=None, timeout=None)¶
Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate and set the
returncodeattribute. The optional input argument should be data to be sent to the child process, orNone, if no data should be sent to the child. If streams were opened in text mode, input must be a string. Otherwise, it must be bytes.communicate()returns a tuple(stdout_data, stderr_data). The data will be strings if streams were opened in text mode; otherwise, bytes.åããã»ã¹ã®æšæºå ¥åã«ããŒã¿ãéãããå Žåã¯ã Popen ãªããžã§ã¯ãã
stdin=PIPEãšæå®ããŠäœæããªããã°ãªããŸãããåãããæ»ãå€ã®ã¿ãã«ããNoneã§ã¯ãªãå€ãååŸããããã«ã¯ãstdout=PIPEãã€/ãŸãã¯stderr=PIPEãæå®ããªããã°ãªããŸãããIf the process does not terminate after timeout seconds, a
TimeoutExpiredexception will be raised. Catching this exception and retrying communication will not lose any output. Supplying input to a subsequent post-timeoutcommunicate()call is in undefined behavior and may become an error in the future.ã¿ã€ã ã¢ãŠããçºçããå Žååããã»ã¹ã¯ kill ãããŸããããããã£ãŠãé©åã«ã¯ãªãŒã³ã¢ãããè¡ãããã«ãæ£åžžã«åäœããã¢ããªã±ãŒã·ã§ã³ã¯åããã»ã¹ã kill ããŠéä¿¡ãçµäºãã¹ãã§ã:
proc = subprocess.Popen(...) try: outs, errs = proc.communicate(timeout=15) except TimeoutExpired: proc.kill() outs, errs = proc.communicate()
After a call to
communicate()raisesTimeoutExpired, do not callwait(). Use an additionalcommunicate()call to finish handling pipes and populate thereturncodeattribute.泚é
åä¿¡ããããŒã¿ã¯ã¡ã¢ãªã«ãããã¡ãŒãããŸãããã®ãããè¿ãããããŒã¿ã倧ããããããã¯å¶éããªããããªå Žåã¯ãã®ã¡ãœããã䜿ãã¹ãã§ã¯ãããŸããã
ããŒãžã§ã³ 3.3 ã§å€æŽ: timeout ã远å ãããŸãã
- Popen.send_signal(signal)¶
signal ã·ã°ãã«ãåããã»ã¹ã«éããŸãã
Do nothing if the process completed.
泚é
Windows ã§ã¯ãSIGTERM ã¯
terminate()ã®å¥åã§ããCTRL_C_EVENT ãš CTRL_BREAK_EVENT ããCREATE_NEW_PROCESS_GROUPãå«ã creationflags ã§å§ãŸã£ããããã»ã¹ã«éããŸãã
- Popen.terminate()¶
Stop the child. On POSIX OSs the method sends
SIGTERMto the child. On Windows the Win32 API functionTerminateProcess()is called to stop the child.
- Popen.kill()¶
åããã»ã¹ã kill ããŸããPOSIX OS ã§ã¯ SIGKILL ã·ã°ãã«ãåããã»ã¹ã«éããŸããWindows ã§ã¯ã
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 ã§ã -- ããã°ã©ã åŒæ°ã®ã·ãŒã±ã³ã¹ãŸã㯠1 åã®æååã«ãªããŸããAdded in version 3.3.
- Popen.stdin¶
If the stdin argument was
PIPE, this attribute is a writeable stream object as returned byopen(). If the encoding or errors arguments were specified or the text or universal_newlines argument wasTrue, the stream is a text stream, otherwise it is a byte stream. If the stdin argument was notPIPE, this attribute isNone.
- Popen.stdout¶
If the stdout argument was
PIPE, this attribute is a readable stream object as returned byopen(). 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 wasTrue, the stream is a text stream, otherwise it is a byte stream. If the stdout argument was notPIPE, this attribute isNone.
- Popen.stderr¶
If the stderr argument was
PIPE, this attribute is a readable stream object as returned byopen(). 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 wasTrue, the stream is a text stream, otherwise it is a byte stream. If the stderr argument was notPIPE, this attribute isNone.
èŠå
.stdin.write, .stdout.read, .stderr.read ãå©çšãããšãå¥ã®ãã€ãã® OS ãã€ããããã¡ãŒããã£ã±ãã«ãªã£ãŠãããããã¯ãçºçããæãããããŸãããããé¿ããããã«ã¯ communicate() ãå©çšããŠãã ããã
- Popen.pid¶
åããã»ã¹ã®ããã»ã¹ ID ãå ¥ããŸãã
shell åŒæ°ã
Trueã«èšå®ããå Žåã¯ãçæãããã·ã§ã«ã®ããã»ã¹ ID ã«ãªããŸãã
- Popen.returncode¶
The child return code. Initially
None,returncodeis set by a call to thepoll(),wait(), orcommunicate()methods if they detect that the process has terminated.A
Nonevalue indicates that the process hadn't yet terminated at the time of the last method call.è² ã®å€
-Nã¯åããã»ã¹ãã·ã°ãã«Nã«ããäžæ¢ãããããããšã瀺ããŸã (POSIX ã®ã¿)ãWhen
shell=True, the return code reflects the exit status of the shell itself (e.g./bin/sh), which may map signals to codes such as128+N. See the documentation of the shell (for example, the Bash manual's Exit Status) for details.
Windows Popen ãã«ããŒÂ¶
STARTUPINFO ã¯ã©ã¹ãšä»¥äžã®å®æ°ã¯ãWindows ã®ã¿ã§å©çšã§ããŸãã
- class subprocess.STARTUPINFO(*, dwFlags=0, hStdInput=None, hStdOutput=None, hStdError=None, wShowWindow=0, lpAttributeList=None)¶
Partial support of the Windows STARTUPINFO structure is used for
Popencreation. The following attributes can be set by passing them as keyword-only arguments.ããŒãžã§ã³ 3.7 ã§å€æŽ: ããŒã¯ãŒãå°çšåŒæ°ã®ãµããŒãã远å ãããŸããã
- dwFlags¶
ç¹å®ã®
STARTUPINFOã®å±æ§ããããã»ã¹ããŠã£ã³ããŠãçæãããšãã«äœ¿ãããããæ±ºå®ããããããã£ãŒã«ãã§ã:si = subprocess.STARTUPINFO() si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
- hStdInput¶
dwFlagsãSTARTF_USESTDHANDLESãæå®ããã°ããã®å±æ§ãããã»ã¹ã®æšæºå ¥ååŠçã§ããSTARTF_USESTDHANDLESãæå®ãããªããã°ãæšæºå ¥åã®ããã©ã«ãã¯ããŒããŒããããã¡ãŒã§ãã
- hStdOutput¶
dwFlagsãSTARTF_USESTDHANDLESãæå®ããã°ããã®å±æ§ãããã»ã¹ã®æšæºåºååŠçã§ããããã§ãªããã°ããã®å±æ§ã¯ç¡èŠãããæšæºåºåã®ããã©ã«ãã¯ã³ã³ãœãŒã«ãŠã£ã³ããŠã®ãããã¡ãŒã§ãã
- hStdError¶
dwFlagsãSTARTF_USESTDHANDLESãæå®ããã°ããã®å±æ§ãããã»ã¹ã®æšæºãšã©ãŒåŠçã§ããããã§ãªããã°ããã®å±æ§ã¯ç¡èŠãããæšæºãšã©ãŒåºåã®ããã©ã«ãã¯ã³ã³ãœãŒã«ãŠã£ã³ããŠã®ãããã¡ãŒã§ãã
- wShowWindow¶
dwFlagsãSTARTF_USESHOWWINDOWãæå®ããã°ããã®å±æ§ã¯ ShowWindow 颿°ã®nCmdShowåŒæ°ã§æå®ãããå€ãªããSW_SHOWDEFAULT以å€ã®ä»»æã®ãã®ã«ã§ããŸãããããããã®å±æ§ã¯ç¡èŠãããŸãããã®å±æ§ã«ã¯
SW_HIDEãæäŸãããŠããŸããããã¯ãPopenãshell=TrueãšããŠåŒã³åºããããšãã«äœ¿ãããŸãã
- lpAttributeList¶
A dictionary of additional attributes for process creation as given in
STARTUPINFOEX, see UpdateProcThreadAttribute.Supported attributes:
- handle_list
Sequence of handles that will be inherited. close_fds must be true if non-empty.
The handles must be temporarily made inheritable by
os.set_handle_inheritable()when passed to thePopenconstructor, elseOSErrorwill be raised with Windows errorERROR_INVALID_PARAMETER(87).èŠå
In a multithreaded process, use caution to avoid leaking handles that are marked inheritable when combining this feature with concurrent calls to other process creation functions that inherit all handles such as
os.system(). This also applies to standard handle redirection, which temporarily creates inheritable handles.
Added in version 3.7.
Windows Constants¶
The subprocess module exposes the following constants.
- subprocess.STD_INPUT_HANDLE¶
æšæºå ¥åããã€ã¹ã§ãããã®åæå€ã¯ãã³ã³ãœãŒã«å ¥åãããã¡ã
CONIN$ã§ãã
- subprocess.STD_OUTPUT_HANDLE¶
æšæºåºåããã€ã¹ã§ãããã®åæå€ã¯ãã¢ã¯ãã£ãã³ã³ãœãŒã«ã¹ã¯ãªãŒã³ã
CONOUT$ã§ãã
- subprocess.STD_ERROR_HANDLE¶
æšæºãšã©ãŒããã€ã¹ã§ãããã®åæå€ã¯ãã¢ã¯ãã£ãã³ã³ãœãŒã«ã¹ã¯ãªãŒã³ã
CONOUT$ã§ãã
- subprocess.SW_HIDE¶
ãŠã£ã³ããŠãé ããŸããå¥ã®ãŠã£ã³ããŠãã¢ã¯ãã£ãã«ãªããŸãã
- subprocess.STARTF_USESTDHANDLES¶
è¿œå æ å ±ãä¿æããã
STARTUPINFO.hStdInput,STARTUPINFO.hStdOutput, ããã³STARTUPINFO.hStdError屿§ãæå®ããŸãã
- subprocess.STARTF_USESHOWWINDOW¶
è¿œå æ å ±ãä¿æããã
STARTUPINFO.wShowWindow屿§ãæå®ããŸãã
- subprocess.STARTF_FORCEONFEEDBACK¶
A
STARTUPINFO.dwFlagsparameter to specify that the Working in Background mouse cursor will be displayed while a process is launching. This is the default behavior for GUI processes.Added in version 3.13.
- subprocess.STARTF_FORCEOFFFEEDBACK¶
A
STARTUPINFO.dwFlagsparameter to specify that the mouse cursor will not be changed when launching a process.Added in version 3.13.
- subprocess.CREATE_NEW_CONSOLE¶
æ°ããããã»ã¹ãã芪ããã»ã¹ã®ã³ã³ãœãŒã«ãç¶æ¿ãã (ããã©ã«ã) ã®ã§ã¯ãªããæ°ããã³ã³ãœãŒã«ãæã¡ãŸãã
- subprocess.CREATE_NEW_PROCESS_GROUP¶
æ°ããããã»ã¹ã°ã«ãŒããçæãããããšãæå®ãã
Popencreationflagsãã©ã¡ãŒã¿ãŒã§ãããã®ãã©ã°ã¯ããµãããã»ã¹ã§os.kill()ã䜿ãã®ã«å¿ èŠã§ããCREATE_NEW_CONSOLEãæå®ãããŠãããããã®ãã©ã°ã¯ç¡èŠãããŸãã
- subprocess.ABOVE_NORMAL_PRIORITY_CLASS¶
A
Popencreationflagsparameter to specify that a new process will have an above average priority.Added in version 3.7.
- subprocess.BELOW_NORMAL_PRIORITY_CLASS¶
A
Popencreationflagsparameter to specify that a new process will have a below average priority.Added in version 3.7.
- subprocess.HIGH_PRIORITY_CLASS¶
A
Popencreationflagsparameter to specify that a new process will have a high priority.Added in version 3.7.
- subprocess.IDLE_PRIORITY_CLASS¶
A
Popencreationflagsparameter to specify that a new process will have an idle (lowest) priority.Added in version 3.7.
- subprocess.NORMAL_PRIORITY_CLASS¶
A
Popencreationflagsparameter to specify that a new process will have a normal priority. (default)Added in version 3.7.
- subprocess.REALTIME_PRIORITY_CLASS¶
A
Popencreationflagsparameter to specify that a new process will have realtime priority. You should almost never use REALTIME_PRIORITY_CLASS, because this interrupts system threads that manage mouse input, keyboard input, and background disk flushing. This class can be appropriate for applications that "talk" directly to hardware or that perform brief tasks that should have limited interruptions.Added in version 3.7.
- subprocess.CREATE_NO_WINDOW¶
A
Popencreationflagsparameter to specify that a new process will not create a window.Added in version 3.7.
- subprocess.DETACHED_PROCESS¶
A
Popencreationflagsparameter to specify that a new process will not inherit its parent's console. This value cannot be used with CREATE_NEW_CONSOLE.Added in version 3.7.
- subprocess.CREATE_DEFAULT_ERROR_MODE¶
A
Popencreationflagsparameter to specify that a new process does not inherit the error mode of the calling process. Instead, the new process gets the default error mode. This feature is particularly useful for multithreaded shell applications that run with hard errors disabled.Added in version 3.7.
å€ã髿°Žæº API¶
Python 3.5 ããåã®ããŒãžã§ã³ã§ã¯ããµãããã»ã¹ã«å¯ŸããŠä»¥äžã® 3 ã€ã®é¢æ°ãããªã髿°Žæº API ãçšæãããŠããŸãããçŸåšå€ãã®å Žå run() ã®äœ¿çšã§æžã¿ãŸãããæ¢åã®å€ãã®ã³ãŒãã§ã¯ãããã®é¢æ°ã䜿çšãããŠããŸãã
- subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs)¶
args ã§æå®ãããã³ãã³ããå®è¡ããŸããã³ãã³ãã®çµäºãåŸ ã¡ã
returncode屿§ãè¿ããŸããCode needing to capture stdout or stderr should use
run()instead:run(...).returncode
To suppress stdout or stderr, supply a value of
DEVNULL.äžèšã®åŒæ°ã¯ããã䜿ããããã®ã ã瀺ããŠããŸãã颿°ã®å šäœ¿çšæ³ã¯
Popenã³ã³ã¹ãã©ã¯ã¿ãŒã®å 容ãšåãã«ãªããŸã - ãã®é¢æ°ã¯ããã®ã€ã³ã¿ãŒãã§ãŒã¹ã«çŽæ¥æå®ããã timeout 以å€ã¯äžããããå šåŒæ°ãæž¡ããŸããæ³šé
ãã®é¢æ°ã䜿çšããéã¯
stdout=PIPEããã³stderr=PIPEã䜿çšããªãã§ãã ãããåããã»ã¹ã OS ã®ãã€ããããã¡ãŒãåããŠããŸãã»ã©ã®åºåããŒã¿ãçæããå Žåããã€ãããã¯èªã¿èŸŒãŸããªãã®ã§ãåããã»ã¹ããããã¯ãããããšããããŸããããŒãžã§ã³ 3.3 ã§å€æŽ: timeout ã远å ãããŸãã
ããŒãžã§ã³ 3.12 ã§å€æŽ:
shell=Trueã®ãšãã®Windowsã·ã§ã«æ€çŽ¢é åºã倿ŽããŸãããã«ã¬ã³ããã£ã¬ã¯ããªãš%PATH%ã¯ã%COMSPEC%ãš%SystemRoot%\System32\cmd.exeã«çœ®ãæããããŸãããããã«ãããcmd.exeãšããååã®æªæã®ããããã°ã©ã ãã«ã¬ã³ããã£ã¬ã¯ããªã«ããããããŠããåäœããªããªããŸããã
- 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. TheCalledProcessErrorobject will have the return code in thereturncodeattribute. Ifcheck_call()was unable to start the process it will propagate the exception that was raised.Code needing to capture stdout or stderr should use
run()instead:run(..., check=True)
To suppress stdout or stderr, supply a value of
DEVNULL.äžèšã®åŒæ°ã¯ããã䜿ããããã®ã ã瀺ããŠããŸãã颿°ã®å šäœ¿çšæ³ã¯
Popenã³ã³ã¹ãã©ã¯ã¿ãŒã®å 容ãšåãã«ãªããŸã - ãã®é¢æ°ã¯ããã®ã€ã³ã¿ãŒãã§ãŒã¹ã«çŽæ¥æå®ããã timeout 以å€ã¯äžããããå šåŒæ°ãæž¡ããŸããæ³šé
ãã®é¢æ°ã䜿çšããéã¯
stdout=PIPEããã³stderr=PIPEã䜿çšããªãã§ãã ãããåããã»ã¹ã OS ã®ãã€ããããã¡ãŒãåããŠããŸãã»ã©ã®åºåããŒã¿ãçæããå Žåããã€ãããã¯èªã¿èŸŒãŸããªãã®ã§ãåããã»ã¹ããããã¯ãããããšããããŸããããŒãžã§ã³ 3.3 ã§å€æŽ: timeout ã远å ãããŸãã
ããŒãžã§ã³ 3.12 ã§å€æŽ:
shell=Trueã®ãšãã®Windowsã·ã§ã«æ€çŽ¢é åºã倿ŽããŸãããã«ã¬ã³ããã£ã¬ã¯ããªãš%PATH%ã¯ã%COMSPEC%ãš%SystemRoot%\System32\cmd.exeã«çœ®ãæããããŸãããããã«ãããcmd.exeãšããååã®æªæã®ããããã°ã©ã ãã«ã¬ã³ããã£ã¬ã¯ããªã«ããããããŠããåäœããªããªããŸããã
- 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)¶
åŒæ°ã§ã³ãã³ããå®è¡ãããã®åºåãè¿ããŸãã
ã³ãã³ãã®ãªã¿ãŒã³ã³ãŒããéãŒããªãã°
CalledProcessErroräŸå€ãéåºãããŸããCalledProcessErrorãªããžã§ã¯ãã«ã¯ããªã¿ãŒã³ã³ãŒããreturncode屿§ã«ãã³ãã³ãããã®åºåãoutput屿§ã«ãããããæ ŒçŽãããŠããŸããããã¯æ¬¡ãšç䟡ã§ã:
run(..., check=True, stdout=PIPE).stdout
The arguments shown above are merely some common ones. The full function signature is largely the same as that of
run()- most arguments are passed directly through to that interface. One API deviation fromrun()behavior exists: passinginput=Nonewill behave the same asinput=b''(orinput='', depending on other arguments) rather than using the parent's standard input file handle.ããã©ã«ãã§ããã®é¢æ°ã¯ããŒã¿ããšã³ã³ãŒãããããã€ããšããŠè¿ããŸããåºåãããããŒã¿ã®å®éã®ãšã³ã³ãŒãã¯èµ·åãããŠããã³ãã³ãã«äŸåãããããããã¹ããžã®ãã³ãŒãã¯éåžžã¢ããªã±ãŒã·ã§ã³ã¬ãã«ã§æ±ãå¿ èŠããããŸãã
This behaviour may be overridden by setting text, encoding, errors, or universal_newlines to
Trueas described in ãã䜿ãããåŒæ° andrun().æšæºãšã©ãŒåºåãçµæã«å«ããã«ã¯ã
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'
Added in version 3.1.
ããŒãžã§ã³ 3.3 ã§å€æŽ: timeout ã远å ãããŸãã
ããŒãžã§ã³ 3.4 ã§å€æŽ: ããŒã¯ãŒãåŒæ° input ã远å ãããŸããã
ããŒãžã§ã³ 3.6 ã§å€æŽ: encoding and errors were added. See
run()for details.Added in version 3.7: text ããuniversal_newlines ã®ããèªã¿ãããå¥åãšããŠè¿œå ãããŸããã
ããŒãžã§ã³ 3.12 ã§å€æŽ:
shell=Trueã®ãšãã®Windowsã·ã§ã«æ€çŽ¢é åºã倿ŽããŸãããã«ã¬ã³ããã£ã¬ã¯ããªãš%PATH%ã¯ã%COMSPEC%ãš%SystemRoot%\System32\cmd.exeã«çœ®ãæããããŸãããããã«ãããcmd.exeãšããååã®æªæã®ããããã°ã©ã ãã«ã¬ã³ããã£ã¬ã¯ããªã«ããããããŠããåäœããªããªããŸããã
Replacing Older Functions with the subprocess Module¶
ãã®ç¯ã§ã¯ã "a becomes b" ãšæžãããŠãããã®ã¯ a ã®ä»£æ¿ãšã㊠b ã䜿ãããšããããšã衚ããŸãã
泚é
ãã®ç¯ã§ç޹ä»ãããŠãã "a" 颿°ã¯å
šãŠãå®è¡ããããã°ã©ã ãèŠã€ãããªããšã㯠(ãããã) éãã«çµäºããŸããããã«å¯Ÿã㊠"b" ä»£æ¿ææ®µã¯ OSError äŸå€ãéåºããŸãã
ãŸããèŠæ±ãããæäœãéãŒãã®çµäºã³ãŒããè¿ããå Žåãcheck_output() ã䜿çšãã眮ãæã㯠CalledProcessError ã§å€±æããŸãããã®åºåã¯ãéåºãããäŸå€ã® output 屿§ãšããŠå©çšå¯èœã§ãã
In the following examples, we assume that the relevant functions have already
been imported from the subprocess module.
Replacing /bin/sh shell command substitution¶
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.stdout.close() ã®åŒã³åºãã¯ãp1 ã p2 ã®åã«ååšããå Žåã«ãp1 ã SIGPIPE ãåãåãããã«éèŠã§ãã
ãããã¯ãä¿¡é Œãããå ¥åã«å¯ŸããŠã¯ãã·ã§ã«èªèº«ã®ãã€ãã©ã€ã³ãµããŒããçŽæ¥äœ¿çšããããšãã§ããŸã:
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 ofos.system().The
os.system()function ignores SIGINT and SIGQUIT signals while the command is running, but the caller must do this separately when using thesubprocessmodule.
ããçŸå®çãªäŸã§ã¯ãããªãã§ããã:
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"})
Replacing os.popen()¶
çµäºã³ãŒããã³ããªã³ã°ã¯ä»¥äžã®ããã«è§£éããŸã:
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")
ã¬ã¬ã·ãŒãªã·ã§ã«åŒã³åºã颿°Â¶
ãã®ã¢ãžã¥ãŒã«ã§ã¯ã以äžã®ãã㪠2.x commands ã¢ãžã¥ãŒã«ããã®ã¬ã¬ã·ãŒé¢æ°ãæäŸããŠããŸãããããã®æäœã¯ãæé»çã«ã·ã¹ãã ã·ã§ã«ãèµ·åããŸãããŸããã»ãã¥ãªãã£ã«é¢ããŠäžè¿°ããä¿èšŒãäŸå€åŠçäžè²«æ§ã¯ããããã®é¢æ°ã§ã¯æå¹ã§ã¯ãããŸããã
- subprocess.getstatusoutput(cmd, *, encoding=None, errors=None)¶
ã·ã§ã«äžã® cmd ãå®è¡ããŠ
(exitcode, output)ãè¿ããŸããExecute the string cmd in a shell with
check_output()and return a 2-tuple(exitcode, output). encoding and errors are used to decode output; see the notes on ãã䜿ãããåŒæ° for more details.A trailing newline is stripped from the output. The exit code for the command can be interpreted as the return code of subprocess. Example:
>>> 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 ã§å€æŽ: Windows ã®ãµããŒãã远å ãããŸããã
The function now returns (exitcode, output) instead of (status, output) as it did in Python 3.3.3 and earlier. exitcode has the same value as
returncode.ããŒãžã§ã³ 3.11 ã§å€æŽ: encoding ãš errors ãåŒæ°ã«è¿œå ãããŸããã
- subprocess.getoutput(cmd, *, encoding=None, errors=None)¶
ã·ã§ã«äžã® cmd ãå®è¡ããŠåºå (stdout ãš stderr) ãè¿ããŸãã
getstatusoutput()ã«äŒŒãŠããŸãããçµäºã³ãŒãã¯ç¡èŠãããã³ãã³ãã®åºåã®ã¿ãè¿ããŸããäŸãã°:>>> subprocess.getoutput('ls /bin/ls') '/bin/ls'
Availability: Unix, Windows.
ããŒãžã§ã³ 3.3.4 ã§å€æŽ: Windowsã§å©çšå¯èœã«ãªããŸãã
ããŒãžã§ã³ 3.11 ã§å€æŽ: encoding ãš errors ãåŒæ°ã«è¿œå ãããŸããã
泚é¶
Timeout Behavior¶
When using the timeout parameter in functions like run(),
Popen.wait(), or Popen.communicate(),
users should be aware of the following behaviors:
Process Creation Delay: The initial process creation itself cannot be interrupted on many platform APIs. This means that even when specifying a timeout, you are not guaranteed to see a timeout exception until at least after however long process creation takes.
Extremely Small Timeout Values: Setting very small timeout values (such as a few milliseconds) may result in almost immediate
TimeoutExpiredexceptions because process creation and system scheduling inherently require time.
Windows ã«ãããåŒæ°ã·ãŒã±ã³ã¹ããæååãžã®å€æÂ¶
Windows ã§ã¯ã args ã·ãŒã±ã³ã¹ã¯ä»¥äžã® (MS C ã©ã³ã¿ã€ã ã§äœ¿ãããèŠåã«å¯Ÿå¿ãã) èŠåã䜿ã£ãŠè§£æã§ããæååã«å€æãããŸã:
åŒæ°ã¯ãã¹ããŒã¹ãã¿ãã®ã©ã¡ããã®ç©ºçœã§åããããŸãã
ããã«ã¯ãªãŒããŒã·ã§ã³ããŒã¯ã§å²ãŸããæååã¯ã空çœãå«ãŸããŠãããšããŠã 1 ã€ã®åŒæ°ãšããŠè§£éãããŸããã¯ãªãŒããããæååã¯åŒæ°ã«åã蟌ããŸãã
ããã¯ã¹ã©ãã·ã¥ã«ç¶ãããã«ã¯ãªãŒããŒã·ã§ã³ããŒã¯ã¯ããªãã©ã«ã®ããã«ã¯ãªãŒããŒã·ã§ã³ããŒã¯ãšè§£éãããŸãã
ããã¯ã¹ã©ãã·ã¥ã¯ãããã«ã¯ãªãŒããŒã·ã§ã³ãç¶ããªãéãããªãã©ã«ãšããŠè§£éãããŸãã
è€æ°ã®ããã¯ã¹ã©ãã·ã¥ã«ããã«ã¯ãªãŒããŒã·ã§ã³ããŒã¯ãç¶ããªããããã¯ã¹ã©ãã·ã¥ 2 ã€ã§ 1 ã€ã®ããã¯ã¹ã©ãã·ã¥æåãšè§£éãããŸããããã¯ã¹ã©ãã·ã¥ã®æ°ã奿°ãªããæåŸã®ããã¯ã¹ã©ãã·ã¥ã¯èŠå 3 ã«åŸã£ãŠç¶ãããã«ã¯ãªãŒããŒã·ã§ã³ããŒã¯ããšã¹ã±ãŒãããŸãã
åè
shlexã³ãã³ãã©ã€ã³ãè§£æããããšã¹ã±ãŒãããããã颿°ãæäŸããã¢ãžã¥ãŒã«ã
Disable use of 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.
subprocess._USE_POSIX_SPAWN = False # See CPython issue gh-NNNNNN.
It is safe to set this to false on any Python version. It will have no effect on older or newer versions where unsupported. Do not assume the attribute is available to read. Despite the name, a true value does not indicate 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.
Added in version 3.8: _USE_POSIX_SPAWN