[python]如何调用shell命令
2016-07-17 11:15
513 查看
在近期的工作,需要使用python实现一解决方案,中间经常用到shell命令,就进行了一些总结.
对于像ls或cat等命令。
但是无法获得命令执行的状态。
获取输出内容
str=os.popen(command).read()
commands.getstatusoutput(cmd)
返回(status, output).
commands.getoutput(cmd)
只返回输出结果
commands.getstatus(file)
返回ls -ld file的执行结果字符串,调用了getoutput
例:
subprocess.call(command,shell=True)
subprocess.Popen(command, shell=True)
如果command不是一个可执行文件,shell=True不可省。
使用subprocess模块可以创建新的进程,可以与新建进程的输入/输出/错误管道连通,并可以获得新建进程执行的返回状态。使用subprocess模块的目的是替代os.system()、os.popen*()、commands.*等旧的函数或模块。
最简单的方法是使用
class subprocess.Popen(command,shell=True)。
Popen类有Popen.stdin,Popen.stdout,Popen.stderr三个有用的属性,可以实现与子进程的通信。
1. os.system(command)
在python中运行command命令,并返回command命令执行完毕后的退出状态。在执行command命令时需要重新打开一个终端,只能获取退出状态,但无法保存command命令的执行结果。比如命令,ls、cat都无法获取其输出结果。importos os.system(command)
2. os.popen(command,mode)
popen函数允许一个程序将另一个程序作为新进程启动,并可以传递数据给它或者通过它接收数据。command字符串是要运行的程序名和相应参数(比如:ls或ls -l),mode必须是 r 或w。如果是r,被调用程序的输出可以被调用它的程序使用;如果是w,调用程序就可以用fwrite向被调用程序发送数据作为它在标准输入流上的输入。对于像ls或cat等命令。
但是无法获得命令执行的状态。
importos os.popen(command, mode)
获取输出内容
str=os.popen(command).read()
3. commands 模块
此模块主要有如下方法:commands.getstatusoutput(cmd)
返回(status, output).
commands.getoutput(cmd)
只返回输出结果
commands.getstatus(file)
返回ls -ld file的执行结果字符串,调用了getoutput
例:
>>> import commands >>> commands.getstatusoutput('ls /bin/ls') (0, '/bin/ls') >>> commands.getstatusoutput('cat /bin/junk') (256, 'cat: /bin/junk: No such file or directory') >>> commands.getstatusoutput('/bin/junk') (256, 'sh: /bin/junk: not found') >>> commands.getoutput('ls /bin/ls') '/bin/ls' >>> commands.getstatus('/bin/ls') '-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'
4. subprocess模块
subprocess.call(["some_command","some_argument","another_argument_or_path"])subprocess.call(command,shell=True)
subprocess.Popen(command, shell=True)
如果command不是一个可执行文件,shell=True不可省。
使用subprocess模块可以创建新的进程,可以与新建进程的输入/输出/错误管道连通,并可以获得新建进程执行的返回状态。使用subprocess模块的目的是替代os.system()、os.popen*()、commands.*等旧的函数或模块。
最简单的方法是使用
class subprocess.Popen(command,shell=True)。
Popen类有Popen.stdin,Popen.stdout,Popen.stderr三个有用的属性,可以实现与子进程的通信。
相关文章推荐
- linux shell 编程(三)
- linux shell 编程(二)
- 【Linux系列】Ubuntu ping通,xshell无法连接
- Powershell下设置环境变量
- UVA 10152 ShellSort
- jq学习使用基础笔记
- shell脚本学习---nohup
- shell之lvm
- hbase的内容查询
- 使用bash on windows
- shell编程基础笔记
- linux shell 编程(一)
- linux--vim、shell(2)
- 常用到的一些Shell,总有你需要的
- linux shell exit 值
- Shell 学习(三) 数组
- Shell 学习(二) 关键字:数据类型 字符串
- adb shell查看任务栈中Activity的排列
- /bin/sh^M:bad interpreter
- 【AD】AD域Powershell批量添加用户组组织单元20160208