python中subprocess模块级方法的介绍(附代码)
Mar 27, 2019 am 09:48 AM本篇文章给大家带来的内容是关于python中subprocess模块级方法的介绍(附代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
subprocess.run()
运行并等待args参数指定的指令完成,返回CompletedProcess实例。
参数:(*popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs)。除input, capture_output, timeout, check,其他参数与Popen构造器参数一致。
capture_output:如果设置为True,表示重定向stdout和stderr到管道,且不能再传递stderr或stdout参数,否则抛出异常。
input:input参数将作为子进程的标准输入传递给Popen.communicate()方法,必须是string(需要指定encoding或errors参数,或者设置text为True)或byte类型。非None的input参数不能和stdin参数一起使用,否则将抛出异常,构造Popen实例的stdin参数将指定为subprocess.PIPE。
timeout:传递给Popen.communicate()方法。
check:如果设置为True,进程执行返回非0状态码将抛出CalledProcessError异常。
# 源码 def run(*popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs): if input is not None: if 'stdin' in kwargs: raise ValueError('stdin and input arguments may not both be used.') kwargs['stdin'] = PIPE if capture_output: if ('stdout' in kwargs) or ('stderr' in kwargs): raise ValueError('stdout and stderr arguments may not be used ' 'with capture_output.') kwargs['stdout'] = PIPE kwargs['stderr'] = PIPE with Popen(*popenargs, **kwargs) as process: try: stdout, stderr = process.communicate(input, timeout=timeout) except TimeoutExpired: process.kill() stdout, stderr = process.communicate() raise TimeoutExpired(process.args, timeout, output=stdout, stderr=stderr) except: # Including KeyboardInterrupt, communicate handled that. process.kill() # We don't call process.wait() as .__exit__ does that for us. raise retcode = process.poll() if check and retcode: raise CalledProcessError(retcode, process.args, output=stdout, stderr=stderr) return CompletedProcess(process.args, retcode, stdout, stderr)
python3.5版本前,call(), check_all(), checkoutput()三种方法构成了subprocess模块的高级API。
subprocess.call()
运行并等待args参数指定的指令完成,返回执行状态码(Popen实例的returncode属性)。
参数:(*popenargs, timeout=None, **kwargs)。与Popen构造器参数基本相同,除timeout外的所有参数都将传递给Popen接口。
调用call()函数不要使用stdout=PIPE或stderr=PIPE,因为如果子进程生成了足量的输出到管道填满OS管道缓冲区,子进程将因不能从管道读取数据而导致阻塞。
# 源码 def call(*popenargs, timeout=None, **kwargs): with Popen(*popenargs, **kwargs) as p: try: return p.wait(timeout=timeout) except: p.kill() p.wait() raise
subprocess.check_call()
运行并等待args参数指定的指令完成,返回0状态码或抛出CalledProcessError异常,该异常的cmd和returncode属性可以查看执行异常的指令和状态码。
参数:(*popenargs, **kwargs)。全部参数传递给call()函数。
注意事项同call()
# 源码 def check_call(*popenargs, **kwargs): retcode = call(*popenargs, **kwargs) if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] raise CalledProcessError(retcode, cmd) return 0
subprocess.check_output()
运行并等待args参数指定的指令完成,返回标准输出(CompletedProcess实例的stdout属性),类型默认是byte字节,字节编码可能取决于执行的指令,设置universal_newlines=True可以返回string类型的值。
如果执行状态码非0,将抛出CalledProcessError异常。
参数:(*popenargs, timeout=None, **kwargs)。全部参数传递给run()函数,但不支持显示地传递input=None继承父进程的标准输入文件句柄。
要在返回值中捕获标准错误,设置stderr=subprocess.STDOUT;也可以将标准错误重定向到管道stderr=subprocess.PIPE,通过CalledProcessError异常的stderr属性访问。
# 源码 def check_output(*popenargs, timeout=None, **kwargs): if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') if 'input' in kwargs and kwargs['input'] is None: # Explicitly passing input=None was previously equivalent to passing an # empty string. That is maintained here for backwards compatibility. kwargs['input'] = '' if kwargs.get('universal_newlines', False) else b'' return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, **kwargs).stdout
subprocess模块还提供了python2.x版本中commands模块的相关函数。
subprocess.getstatusoutput(cmd)
实际上是调用check_output()函数,在shell中执行string类型的cmd指令,返回(exitcode, output)形式的元组,output(包含stderr和stdout)是使用locale encoding解码的字符串,并删除了结尾的换行符。
# 源码 try: data = check_output(cmd, shell=True, universal_newlines=True, stderr=STDOUT) exitcode = 0 except CalledProcessError as ex: data = ex.output exitcode = ex.returncode if data[-1:] == '\n': data = data[:-1] return exitcode, data
subprocess.getoutput(cmd)
与getstatusoutput()类似,但结果只返回output。
本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的python视频教程栏目!
Atas ialah kandungan terperinci python中subprocess模块级方法的介绍(附代码). Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Artikel Panas

Alat panas Tag

Artikel Panas

Tag artikel panas

Notepad++7.3.1
Editor kod yang mudah digunakan dan percuma

SublimeText3 versi Cina
Versi Cina, sangat mudah digunakan

Hantar Studio 13.0.1
Persekitaran pembangunan bersepadu PHP yang berkuasa

Dreamweaver CS6
Alat pembangunan web visual

SublimeText3 versi Mac
Perisian penyuntingan kod peringkat Tuhan (SublimeText3)

Topik panas

Apakah kelebihan dan kekurangan templat?

Google AI mengumumkan Gemini 1.5 Pro dan Gemma 2 untuk pembangun

Dengan hanya $250, pengarah teknikal Hugging Face mengajar anda cara memperhalusi Llama 3

Panduan lengkap untuk penyahpepijatan dan analisis fungsi golang

Kongsi beberapa rangka kerja projek berkaitan AI dan LLM sumber terbuka .NET

Bagaimana anda bertanya kepadanya Deepseek
