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>>8
1

2. os.popen()

help(os.system)

2.1 demo

#os.popen(command):这种调用方式是通过管道的方式来实现,函数返回一个file对象,
#里面的内容是脚本输出的内容(可简单理解为echo输出的内容),使用os.popen调用test.sh的情况>> import os
>>> os.popen("./test.sh")
<open file './test.sh', mode 'r' at 0x7f6cbbbee4b0>
>>> f=os.popen("./test.sh")
>>> f
<open file './test.sh', mode 'r' at 0x7f6cbbbee540>
>>> 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 subprocess# Based 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 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: 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: 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

5. 参考文献

https://www.jb51.net/article/186301.htm

python调用bash shell脚本相关推荐

  1. 调用bash shell脚本的方式

    项目中经常要求一些参数可配置的: 因此会定义一个conf.sh脚本, 然后在每个需要的脚本中调用 source ./conf.sh 或者 . /conf.sh的方式. 但是如果脚本逻辑比较复杂, 可能 ...

  2. python调用shell命令-Python怎么运行shell脚本

    Python作为一门脚本语言,有时候需要与shell命令交互式使用,在Python中提供了很多的方法可以调用并执行shell脚本,本文介绍几个简单的方法. Python怎么运行shell脚本 一.os ...

  3. BASH SHELL 脚本基础

    什么是shell     Linux系统的shell作为操作系统的外壳,为用户提供使用操作系统的接口.它是命令语言.命令解释程序及程序设计语言的统称. shell是用户和Linux内核之间的接口程序, ...

  4. linux shell 执行目录,bash shell脚本执行的几种方法

    bash shell 脚本执行的方法有多种,本文作一个总结,供大家学习参考. 假设我们编写好的shell脚本的文件名为hello.sh,文件位置在/data/shell目录中并已有执行权限. 方法一: ...

  5. shell脚本spawn_如何使用child_process.spawn将Python / Ruby / PHP Shell脚本与Node.js集成

    shell脚本spawn There are occasions when running a Python/Ruby/PHP shell script from Node.js is necessa ...

  6. Linux——Bash Shell脚本 for循环

    1.创建和执行Bash Shell脚本 (1)借助Bash Shell环境和脚本编写功能,将Linux命令与shell脚本组合在一起,从而轻松的解决重复而困难的实际问题,Bash shell脚本最简单 ...

  7. python定时任务执行shell脚本切割Nginx日志-慎用

    Python定时任务执行shell脚本切割Nginx日志(慎用) 缘起 我们有一个Nginx服务用来接收埋点上报数据,输出的日志文件比较大,Nginx没有自带日志分割组件,这样输出的日志文件就比较大, ...

  8. python中执行shell脚本之subprocess模块

    一. 最近subprocess使用背景和介绍 因为最近领导要求,在Python端调用大数据的shell脚本,所以需要用到Python来执行shell脚本, 因此需要查看下subprocess模块文档. ...

  9. Shell中要如何调用别的shell脚本

    在Shell中要如何调用别的shell脚本,或别的脚本中的变量,函数呢? 方法一: . ./subscript.sh 方法二: source ./subscript.sh 转载于:https://bl ...

  10. linux如何调试脚本文件目录,如何在Linux下调试Bash Shell脚本的方法

    新手写了一个 hello world 小脚本,如何能调试运行在 Linux 或者类 UNIX 的系统上的 bash shell 脚本呢? 这是 Linux / Unix 系统管理员或新用户最常问的问题 ...

最新文章

  1. 【数据结构】堆,大根堆,小根堆,优先队列 详解
  2. 基于Pytorch再次解读LeNet-5现代卷积神经网络
  3. jdbc java数据库连接 3)Statement接口之执行DDL和DML语句的简化
  4. python怎么引用多行输入_python调用shell返回两行第二行需要输入密码怎么办?import os os.syst...
  5. 作者:程致远(1991-),男,东北大学计算机科学系硕士生
  6. 响应式禁用(Bootstrap PK AmazeUI)
  7. FineUIPro控件库深度解析
  8. 取石子游戏(斐波那契博弈)
  9. 修改官方发行openstack镜像的cloud-init登录方式为账号密码登录
  10. STM32串口接收以及发送大全
  11. STM32——红外遥控器实验
  12. html静态网页实例一(附完整代码)
  13. 树莓派 串口如何使用 以及树莓派引脚对照表
  14. 新闻管理系统(四)封装news表相关
  15. linux怎么模糊查找文件,linux怎么模糊查找一个文件
  16. 安装mysql包有问题_安装mysql数据库及问题解决方法
  17. Win10家庭中文版开机后弹窗无法登录到你的账户点注销没用(解决过程记录)
  18. maven:pom文件详细信息
  19. java NIO BIO和AIO
  20. SU草图大师错误合集

热门文章

  1. 软件数字签名 c语言,C语言实现的SM2数字签名验证
  2. 为什么某些网站有些地方打得开,有些地方打不开?
  3. ubuntu linux 安装报错解决方法E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource tempo
  4. c语言蜂鸣字符,蜂鸣器原理
  5. linux下解压rpm包,linux下 各种解压文件使用方法
  6. CCproxy代理服务器
  7. Python黑客绝技04:Python基础知识2
  8. 股票估值法研究报告_论述股票的估值方法
  9. Java丨策略模式丨模拟充值Q币
  10. 汇编指令:CLD STD MOVS LODS STOS