Python调用shell指令
方法一、使用os模块的system方法:os.system(cmd),其返回值是shell指令运行后返回的状态码,int类型,0表示shell指令成功执行,256表示未找到,该方法适用于shell命令不需要输出内容的场景。
举例说明:
-
列举当前目录下的所有文件。
1 import os
2 val = os.system('ls -al')
3 print val
没有找到时,sh返回的状态码是1,而适用python调用,返回的是:256
方法二、使用os.popen(),该方法以文件的形式返回shell指令运行后的结果,需要获取内容时可使用read()或readlines()方法,举例如下:
方法三、使用commands模块,有三个方法可以使用:
(1)commands.getstatusoutput(cmd),其以字符串的形式返回的是输出结果和状态码,即(status,output)。
(2)commands.getoutput(cmd),返回cmd的输出结果。
(3)commands.getstatus(file),返回ls -l file的执行结果字符串,调用了getoutput,不建议使用此方法
方法四、subprocess模块,允许创建很多子进程,创建的时候能指定子进程和子进程的输入、输出、错误输出管道,执行后能获取输出结果和执行状态。
(1)subprocess.run():python3.5中新增的函数, 执行指定的命令, 等待命令执行完成后返回一个包含执行结果的CompletedProcess类的实例。
(2)subprocess.call():执行指定的命令, 返回命令执行状态, 功能类似os.system(cmd)。
(3)subprocess.check_call():python2.5中新增的函数, 执行指定的命令, 如果执行成功则返回状态码, 否则抛出异常。
说明:subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, universal_newlines=False)
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)
subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)
args:表示shell指令,若以字符串形式给出shell指令,如"ls -l "则需要使shell = Ture。否则默认已数组形式表示shell变量,如"ls","-l"。
当使用比较复杂的shell语句时,可以先使用shlex模块的shlex.split()方法来帮助格式化命令,然后在传递给run()方法或Popen。
附上python2.7中的subprocess模块源码供理解(pycharm查看方法源码,ctrl+左键)。
# Stubs for subprocess
# Based on http://docs.python.org/2/library/subprocess.html and Python 3 stub
from typing import Sequence, Any, Mapping, Callable, Tuple, IO, Union, Optional, List, Text
_FILE = Union[None, int, IO[Any]]
_TXT = Union[bytes, Text]
_CMD = Union[_TXT, Sequence[_TXT]]
_ENV = Union[Mapping[bytes, _TXT], Mapping[Text, _TXT]]
# Same args as Popen.__init__
def call(args: _CMD,
bufsize: int = ...,
executable: _TXT = ...,
stdin: _FILE = ...,
stdout: _FILE = ...,
stderr: _FILE = ...,
preexec_fn: Callable[[], Any] = ...,
close_fds: bool = ...,
shell: bool = ...,
cwd: _TXT = ...,
env: _ENV = ...,
universal_newlines: bool = ...,
startupinfo: Any = ...,
creationflags: int = ...) -> int: ...
def check_call(args: _CMD,
bufsize: int = ...,
executable: _TXT = ...,
stdin: _FILE = ...,
stdout: _FILE = ...,
stderr: _FILE = ...,
preexec_fn: Callable[[], Any] = ...,
close_fds: bool = ...,
shell: bool = ...,
cwd: _TXT = ...,
env: _ENV = ...,
universal_newlines: bool = ...,
startupinfo: Any = ...,
creationflags: int = ...) -> int: ...
# Same args as Popen.__init__ except for stdout
def check_output(args: _CMD,
bufsize: int = ...,
executable: _TXT = ...,
stdin: _FILE = ...,
stderr: _FILE = ...,
preexec_fn: Callable[[], Any] = ...,
close_fds: bool = ...,
shell: bool = ...,
cwd: _TXT = ...,
env: _ENV = ...,
universal_newlines: bool = ...,
startupinfo: Any = ...,
creationflags: int = ...) -> bytes: ...
PIPE = ... # type: int
STDOUT = ... # type: int
class CalledProcessError(Exception):
returncode = 0
# morally: _CMD
cmd = ... # type: Any
# morally: Optional[bytes]
output = ... # type: Any
def __init__(self,
returncode: int,
cmd: _CMD,
output: Optional[bytes] = ...) -> None: ...
class Popen: