Skip to content

subprocess: python 2.7脚本中如何运行shell命令

每次用的时候都要去读一下文档,这次总结一下,记录于此,已备后用。 其实这个主要是用subprocess这个模块。 最普通的,执行命令,但不管命令的输出: import subprocess return_code = subprocess.call(“ls”,”-ltra”], shell=True) 设置”shell=True” 是告诉python在后台生成一个shell进程,然后在此shell进程中执行相应命令。 这样可以利用到shell中的一些特性,但这样做有安全风险,只有传入的命令完全可控时才这样做。   命令的返回值保存在return_code中。输出则直接输出到屏幕(stdout)。 如果需要获取命令的输出,则用subprocess中的check_output, 而非call: output = subprocess.check_output([‘ls’, ‘-l’]) print ‘Have %d bytes in output’ % len(output) print output ## if the command fails, python throws an CalledProcessError 上面的方式中,如果命令的出错输出(如果有的话)仍然会出现在屏幕上。…

Read more
Sidebar