在 Python 开发中经常会需要处理一些 Linux 命令,下面介绍几种常见的处理此类命令模块,以下命令均在 ipython 中进行
1 | In [5]: import os |
1 | In [6]: os.popen('echo "Hello World"') |
1 | In [7]: os.popen('echo "Hello World"').read() |
commands
os 模块可以勉强达到我们想要的效果,但是用起来会很别扭,我们还可以使用 commands 模块提供的 getstatusoutput(), getoutput() 两个方法来完成任务
1 | In [1]: import commands |
getstatusoutput() 方法会返回一个元组 (status, output) 分别为执行状态和结果,这个结果是用字符串的形式将结果呈现出来,而 getoutput() 方法只返回结果
1 | In [3]: commands.getoutput('ls') |
subprocess
在官方文档中 subprocess 模块是被用来替换上边提到的方法的,它可以开启子线程工作,比他们更加灵活。它有非常丰富的使用方法,这里简单介绍输出方法 check_output()
1 | In [13]: import subprocess |
简单的命令没有太大区别,但是执行一些复杂的方法会有所不同
1 | In [15]: subprocess.check_output('echo "hello world"') |
在进行复杂命令时,该方法需要接收一个数组
1 | In [16]: subprocess.check_output(['echo', 'hello world']) |
更多使用方法见文档
最近热读
扫码关注公众号,或搜索公众号“温欣爸比”
及时获取我的最新文章