Python中调用shell

1 简单调用shell命令

os.system(command)

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

2 通过管道

os.popen(command, mode)

打开一个与command进程之间的管道. 这个函数的返回值是一个文件对象, 可以读或者写(由mode决定, mode默认是’r'). 如果mode为’r', 可以使用此函数的返回值调用read()来获取command命令的执行结果.

例如:

写管道:

os.popen('wc -c', 'w').write('hello world') 

读管道:

print os.popen("echo 'hello world' |wc -c").read()

3 commands

import commands
commands.getstatusoutput(command)

使用os.popen()函数执行command命令并返回一个元组(status, output), 分别表示:

  • command命令执行的返回状态(相当于命令行查看$?)
  • 执行结果(相当于命令行输出)

对command的执行实际上是按照{command;} 2>&1的方式, 所以output中包含控制台输出信息或者错误信息. output中不包含尾部的换行符.

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三个有用的属性, 可以实现与子进程的通信.

将调用shell的结果赋值给python变量. 如:

handle = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
print handle.communicate()[0]

>>> import subprocess
>>> path = subprocess.Popen("pwd", shell=True, stdout=subprocess.PIPE)
>>> print(path.communicate()[0])
/proc/4469

 

5 参考

http://blog.sina.cn/dpool/blog/s/blog_5357c0af0100yzet.html?vt=4

http://m.jb51.net/article/43500.htm

http://www.mikewootc.com/wiki/sw_develop/language/python_shell.html

posted @ 2019-03-27 11:19  薏米*  阅读(357)  评论(0编辑  收藏  举报