Python调用shell命令的常用方法

1.os.system(command)

在一个子shell中运行command命令,并返回command命令执行完毕后的退出状态。这实际上是使用C标准库函数system()实现的。这个函数在执行command命令时需要重新打开一个终端,并且无法保存command命令的执行结果。该方法适用于shell命令不需要输出内容的场景。

其返回值是shell指令运行后返回的状态码,int类型,0表示shell指令成功执行,1表示未找到。

2.os.popen(command)

该方法以文件的形式返回shell指令运行后的结果,需要获取内容时可使用read()或readlines()方法。

3.commands.getstatusoutput(command)

(1)commands.getstatusoutput(cmd),其以字符串的形式返回的是输出结果状态码和输出结果,即(status,output)。

>>>import commands
>>>status,output = commands.getstatusoutput('ls')
>>>print(status)
0
>>>print(output)
anaconda-ks.cfg
install.log
install.log.syslog

(2)commands.getoutput(cmd),返回cmd的输出结果。
(3)commands.getstatus(file),返回ls -l file的执行结果字符串,其调用了getoutput,不如直接用getoutput。

4、subprocess模块
使用subprocess模块可以创建新的进程,可以与新建进程的输入/输出/错误管道连通,并可以获得新建进程执行的返回状态。使用subprocess模块的目的是替代os.system()、os.popen*()、commands.*等旧的函数或模块。

(1)subprocess.call(command, shell=True)

返回命令执行状态, 功能类似os.system(cmd)

(2)subprocess.Popen(command, shell=True)

如果command不是一个可执行文件,shell=True是不可省略的。

subprocess.Popen(command, shell=True)会直接输出结果,其返回值也为状态码,0表示执行成功。

从运行结果中看到,父进程在开启子进程之后并没有等待子进程的完成。

可以使用wait()方法等待子进程结束:

 

Popen中还可以对子进程对象进行其他操作:

poll(): 检查进程是否终止,如果终止返回 returncode,否则返回 None。
wait(timeout): 等待子进程终止。
communicate(input,timeout): 和子进程交互,发送和读取数据。
send_signal(singnal): 发送信号到子进程 。
terminate(): 停止子进程,也就是发送SIGTERM信号到子进程。
kill(): 杀死子进程。发送 SIGKILL 信号到子进程。

posted @ 2021-04-28 16:27  迪克推多0  阅读(895)  评论(0编辑  收藏  举报