python调用bash|python调用bash shell脚本方法
目录
- 1. os.system()
- 1.1. demo
- 2. os.popen()
- 2.1 demo
- 3. commands模块
- 4. subprocess
- 4.1 demo
1. os.system()
help(os.system)
1.1. demo
os.system(command):
该方法在调用完shell脚本后,返回一个16位的二进制数,- 低位为杀死所调用脚本的信号号码,高位为脚本的退出状态码,
- 即脚本中exit 1的代码执行后,
os.system
函数返回值的高位数则是1,如果低位数是0的情况下, - 则函数的返回值是0x0100,换算为十进制得到256。
- 要获得
os.system
的正确返回值,可以使用位移运算(将返回值右移8位)还原返回值:
>>> import os>>> os.system("./test.sh")hello python!hello world!256>>> n>>81
【python调用bash|python调用bash shell脚本方法】
2. os.popen()
help(os.system)
2.1 demo
os.popen(command):
这种调用方式是通过管道的方式来实现,函数返回一个file对象,里面的内容是脚本输出的内容(可简单理解为echo输出的内容),使用
os.popen
调用test.sh
的情况>> import os>>> os.popen("./test.sh")>>> f=os.popen("./test.sh")>>> f >>> f.readlines()['hello python!\n', 'hello world!\n']
3. commands模块
- (1)commands.getstatusoutput(cmd),其以字符串的形式返回的是输出结果和状态码,即(status,output)。
- (2)commands.getoutput(cmd),返回cmd的输出结果。
- (3)commands.getstatus(file),返回ls -l file的执行结果字符串,调用了
getoutput
,不建议使用此方法
4. subprocess
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
。4.1 demo
Stubs for subprocessBased on http://docs.python.org/2/library/subprocess.html and Python 3 stubfrom 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 stdoutdef 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: intSTDOUT = ... # type: intclass CalledProcessError(Exception):returncode = 0# morally: _CMDcmd = ... # type: Any# morally: Optional[bytes]output = ... # type: Anydef __init__(self,returncode: int,cmd: _CMD,output: Optional[bytes] = ...) -> None: ...class Popen:stdin = ... # type: Optional[IO[Any]]stdout = ... # type: Optional[IO[Any]]stderr = ... # type: Optional[IO[Any]]pid = 0returncode = 0def __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: AnySTD_OUTPUT_HANDLE = ... # type: AnySTD_ERROR_HANDLE = ... # type: AnySW_HIDE = ... # type: AnySTARTF_USESTDHANDLES = ... # type: AnySTARTF_USESHOWWINDOW = ... # type: AnyCREATE_NEW_CONSOLE = ... # type: AnyCREATE_NEW_PROCESS_GROUP = ... # type: Any
到此这篇关于python调用bash shell脚本方法的文章就介绍到这了,更多相关python调用bash shell脚本内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
文章图片
推荐阅读
- Shell-Bash变量与运算符
- python学习之|python学习之 实现QQ自动发送消息
- 逻辑回归的理解与python示例
- SpringBoot调用公共模块的自定义注解失效的解决
- python自定义封装带颜色的logging模块
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- thinkphp|thinkphp 3.2 如何调用第三方类库
- Python基础|Python基础 - 练习1
- Python爬虫|Python爬虫 --- 1.4 正则表达式(re库)
- Python(pathlib模块)