Python调⽤shell命令常⽤⽅法(4种)
⽅法⼀、使⽤os模块的system⽅法:os.system(cmd),其返回值是shell指令运⾏后返回的状态码,int类型,0表⽰shell指令成功执⾏,256表⽰未到,该⽅法适⽤于shell命令不需要输出内容的场景。
举例说明:
1. 列举当前⽬录下的所有⽂件。
import os
val = os.system('ls -al')
print val
没有到时,sh返回的状态码是1,⽽适⽤python调⽤,返回的是:256
⽅法⼆、使⽤os.popen(),该⽅法以⽂件的形式返回shell指令运⾏后的结果,需要获取内容时可使⽤read()或readlines()⽅法,举例如下:
⽅法三、使⽤commands模块,有三个⽅法可以使⽤:
(1)statusoutput(cmd),其以字符串的形式返回的是输出结果和状态码,即(status,output)。
(2)utput(cmd),返回cmd的输出结果。
(3)status(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 /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: ...
shell脚本返回执行结果
class Popen:
stdin = ... # type: Optional[IO[Any]]
stdout = ... # type: Optional[IO[Any]]
stderr = ... # type: Optional[IO[Any]]
pid = 0
returncode = 0
def __init__(self,
args: _CMD,
bufsize: int = ...,
executable: Optional[_TXT] = ...,
stdin: Optional[_FILE] = ...,
stdout: Optional[_FILE] = ...,
stderr: Optional[_FILE] = ...,
preexec_fn: Optional[Callable[[], Any]] = ...,
close_fds: bool = ...,
shell: bool = ...,
cwd: Optional[_TXT] = ...,
env: Optional[_ENV] = ...,
universal_newlines: bool = ...,
startupinfo: Optional[Any] = ...,
creationflags: int = ...) -> None: ...
def poll(self) -> int: ...
def wait(self) -> int: ...
# morally: -> Tuple[Optional[bytes], Optional[bytes]]
def communicate(self, input: Optional[_TXT] = ...) -> Tuple[Any, Any]: ...
def send_signal(self, signal: int) -> None: ...
def terminate(self) -> None: ...
def kill(self) -> None: ...
def __enter__(self) -> 'Popen': ...
def __exit__(self, type, value, traceback) -> bool: ...
# Windows-only: STARTUPINFO etc.
STD_INPUT_HANDLE = ... # type: Any
STD_OUTPUT_HANDLE = ... # type: Any
STD_ERROR_HANDLE = ... # type: Any
SW_HIDE = ... # type: Any
STARTF_USESTDHANDLES = ... # type: Any
STARTF_USESHOWWINDOW = ... # type: Any
CREATE_NEW_CONSOLE = ... # type: Any
CREATE_NEW_PROCESS_GROUP = ... # type: Any
shell脚本使⽤python脚本的参数
写⼀个hello.sh脚本,需要传⼊两个参数:
执⾏结果如下:
在python脚本中调⽤shell脚本,并传⼊参数,注意参数前后要有空格
执⾏python脚本
到此这篇关于Python调⽤shell命令常⽤⽅法(4种)的⽂章就介绍到这了,更多相关Python调⽤shell命令内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。