除了常见的os.system和os.popen方法,官方强烈推荐使用subprocess来调用系统命令。

这个库用起来其实很简单,按照惯例先贴一下官文关键点:

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle.
For more advanced use cases, the underlying Popen interface can be used directly.

推荐的使用方式是:任何场景下,只要调用run()方法即可,已经封装好了一切。

底层接口Popen也可以直接使用,不过要注意管道堵塞问题。

API说明如下:

subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, ...)

Run the command described by args. Wait for command to complete, then return a CompletedProcess instance. 执行命令,等待执行完成,返回CompletedProcess实例
args is required for all calls and should be a string, or a sequence of program arguments.
If passing a single string, shell must be True.
If shell is True, the specified command will be executed through the shell.
On POSIX with shell=True, the shell defaults to /bin/sh. 默认shell是/bin/sh
subprocess.PIPE
Special value that can be used as the stdin, stdout or stderr argument to Popen and indicates that a pipe to the standard stream should be opened. subprocess.STDOUT
Special value that can be used as the stderr argument to Popen and indicates that standard error should go into the same handle as standard output.
合并错误输出到标准输出
class subprocess.CompletedProcess

The return value from run(), representing a process that has finished.

args
The arguments used to launch the process. This may be a list or a string. returncode
Exit status of the child process. Typically, an exit status of 0 indicates that it ran successfully.
A negative value -N indicates that the child was terminated by signal N (POSIX only). stdout
Captured stdout from the child process. A bytes sequence, or a string if run() was called with an encoding, errors, or text=True.

看不懂英文的同学可以略过API说明,下面来说使用姿势。

这里提供两种传参方式,一种是将要执行的命令以一整个字符串传入,一种是以序列方式传入,具体来说是这样:

subprocess.run(["ls", "-l"])
subprocess.run('ls -l', shell=True)
r = subprocess.run('ls -l', shell=True, stdout=PIPE, stderr=subprocess.STDOUT)
print(r)
print(type(r))
print(r.stdout.decode()) # 获取结果
print(r.returncode)

仅此而已,就这么简单。


关于Popen,简单说几句。

This will deadlock when using stdout=PIPE or stderr=PIPE and the child process generates enough output to a pipe,
such that it blocks waiting for the OS pipe buffer to accept more data. Use Popen.communicate() when using pipes to avoid that.

官文说Popen中使用PIPE可能会造成堵塞,建议使用Popen.communicate()来避免这个问题。

这一点,run()方法已经封装解决了,直接使用run()方法可以不理会这个问题。

解决这个问题还有一个思路,就是不用PIPE。使用临时文件保存输出。

from subprocess import Popen
from tempfile import TemporaryFile with TemporaryFile(mode='w+b') as f: # 使用临时文件保存输出结果,避免死锁
with Popen('ifconfig', shell=True, stdout=f, stderr=subprocess.STDOUT) as proc:
status = proc.wait()
f.seek(0) # 写文件时指针在文末所以读取文件需要移动指针
print(f.read().decode())
print(status)

另外,这个模块里面还有一个老方法可以用来执行命令。

implicitly invoke the system shell.

subprocess.getoutput(cmd)
Return output (stdout and stderr) of executing cmd in a shell.
r = subprocess.getoutput('ls -l')
print(r)
print(type(r))
# <class 'str'>

一句话,请使用subprocess.run()方法,其它可以忽略。

参考:

https://docs.python.org/3/library/subprocess.html

https://docs.python.org/3/library/tempfile.html

调用系统命令之subprocess模块的更多相关文章

  1. 23-[模块]-subprocess模块

    1.调用系统命令 我们经常需要通过Python去执行一条系统命令或脚本,系统的shell命令是独立于你的python进程之外的,每执行一条命令,就是发起一个新进程,通过python调用系统命令或脚本的 ...

  2. python常用模块-调用系统命令模块(subprocess)

    python常用模块-调用系统命令模块(subprocess) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. subproces基本上就是为了取代os.system和os.spaw ...

  3. Python 调用系统命令的模块 Subprocess

    Python 调用系统命令的模块 Subprocess 有些时候需要调用系统内部的一些命令,或者给某个应用命令传不定参数时可以使用该模块. 初识 Subprocess 模块 Subprocess 模块 ...

  4. 使用python的subprocess模块调用linux系统命令

    subprocess模块主要有call().check_call().check_output().Popen()函数,简要描述如下: Main API ======== call(...): Run ...

  5. Python用subprocess的Popen来调用系统命令

    当我们须要调用系统的命令的时候,最先考虑的os模块.用os.system()和os.popen()来进行操作.可是这两个命令过于简单,不能完毕一些复杂的操作,如给执行的命令提供输入或者读取命令的输出, ...

  6. Python使用subprocess的Popen要调用系统命令

    当我们须要调用系统的命令的时候,最先考虑的os模块.用os.system()和os.popen()来进行操作.可是这两个命令过于简单.不能完毕一些复杂的操作,如给执行的命令提供输入或者读取命令的输出, ...

  7. s14 第5天 时间模块 随机模块 String模块 shutil模块(文件操作) 文件压缩(zipfile和tarfile)shelve模块 XML模块 ConfigParser配置文件操作模块 hashlib散列模块 Subprocess模块(调用shell) logging模块 正则表达式模块 r字符串和转译

    时间模块 time datatime time.clock(2.7) time.process_time(3.3) 测量处理器运算时间,不包括sleep时间 time.altzone 返回与UTC时间 ...

  8. Python模块之subprocess--使用Popen来调用系统命令

    当我们需要调用系统的命令的时候,最先考虑的os 模块.用os.system()和os.popen()来进行操作.但是这两个命令过于简单,不能完成一些复杂的操作,如给运行的命令提供输入或者读取命 令的输 ...

  9. Python学习笔记——基础篇【第六周】——Subprocess模块

    执行系统命令 可以执行shell命令的相关模块和函数有: os.system os.spawn* os.popen*          --废弃 popen2.*           --废弃 com ...

随机推荐

  1. Scala学习(五)练习

    Scala中的类&练习 1. 改进Counter类,让它不要在Int.MaxValue时变成负数 程序代码: class Counter { private var value=100 def ...

  2. 线上分享-- 基于DDD的.NET开发框架-ABP介绍

    前言 为了能够帮助.Net开发者开拓视野,更好的把最新的技术应用到工作中,我在3月底受邀到如鹏网.net训练营直播间为各位学弟学妹们进行ABP框架的直播分享.同时为了让更多的.NET开发者了解ABP框 ...

  3. Vue2.0 搭配 axios

    1.安装axios $ npm install axios 2.Demo (1)Get // 为给定 ID 的 user 创建请求 axios.get('/user?ID=12345') .then( ...

  4. Redis未授权访问漏洞的利用及防护

    Redis未授权访问漏洞的利用及防护 什么是Redis未授权访问漏洞? Redis在默认情况下,会绑定在0.0.0.0:6379.如果没有采取相关的安全策略,比如添加防火墙规则.避免其他非信任来源IP ...

  5. CentOS6下OpenLDAP+PhpLdapAdmin基本安装及主从/主主高可用模式部署记录

    下面测试的部署机ip地址为:192.168.10.2051)yum安装OpenLDAP [root@openldap-server ~]# yum install openldap openldap- ...

  6. Code Review —— by12061154Joy

    对结对队友刘丽萍的代码进行了复审: 优点: 1,代码逻辑正确,基本能够完全需求 2,用了不少C#自带的函数,第一次写C#,相信是查阅了不少资料,虽然还有很多地方值得优化,不过第一次能做到这样已经很不错 ...

  7. 【Beta阶段】第八次Scrum Meeting!

    每日任务内容: 本次会议为第八次Scrum Meeting会议~ 由于本次会议项目经理身体不适,未参与会议,会议精神由卤蛋代为转达,其他同学一起参与了会议 队员 昨日完成任务 明日要完成任务 刘乾 今 ...

  8. Linux内核分析第四章 读书笔记

    Linux内核分析第四章 读书笔记 第一部分--进程调度 进程调度:操作系统规定下的进程选取模式 面临问题:多任务选择问题 多任务操作系统就是能同时并发地交互执行多个进程的操作系统,在单处理器机器上这 ...

  9. Leetcode——58.最后一个单词的长度

    给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度. 如果不存在最后一个单词,请返回 0 . 说明:一个单词是指由字母组成,但不包含任何空格的字符串. 示例: 输入: &quo ...

  10. HDOJ2010_水仙花数

    一道水题.一直出现Output Limit Exceeded的原因是在while循环中没有终止条件的时候会自动判断并报错,写的时候忘记加!=EOF结束标识了. HDOJ2010_水仙花数 #inclu ...