subprocess

可以执行shell命令的相关模块和函数有:

os.system
os.spawn
os.popen
 --废弃
popen2.* --废弃
commands.* --废弃,3.x中被移除

import commands

result = commands.getoutput('cmd')   #只返回执行的结果, 忽略返回值.
result = commands.getstatus('cmd')   
返回ls -ld file执行的结果.
result = commands.getstatusoutput('cmd') 
用os.popen()执行命令cmd, 然后返回两个元素的元组(status, result). cmd执行的方式是{ cmd ; }2>&1, 这样返回结果里面就会包含标准输出和标准错误.
例子
>>> subprocess.getstatusoutput('pwd')
(0, '/home/ronny')
>>> subprocess.getoutput('pwd')
'/home/ronny'
>>> subprocess.getstatus('pwd')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'subprocess' has no attribute 'getstatus'

以上执行shell命令的相关的模块和函数的功能均在 subprocess 模块中实现,并提供了更丰富的功能。

(1) call

执行命令,返回状态码(命令正常执行返回0,报错则返回1)

ret1=subprocess.call("ifconfig")
ret2=subprocess.call("ipconfig")    #python3.5不是这样,依然会抛出异常导致无法对ret2赋值
print(ret1) #0
print(ret2) #1 ret = subprocess.call(["ls", "-l"], shell=False) #shell为False的时候命令必须分开写
ret = subprocess.call("ls -l", shell=True)

(2) check_call

执行命令,如果执行成功则返回状态码0,否则抛异常

subprocess.check_call(["ls", "-l"])
subprocess.check_call("exit 1", shell=True)

(3) check_output

执行命令,如果执行成功则返回执行结果,否则抛异常

subprocess.check_output(["echo", "Hello World!"])
subprocess.check_output("exit 1", shell=True)

(4) subprocess.Popen(...)

用于执行复杂的系统命令

参数 注释
args shell命令,可以是字符串或者序列类型(如:list,元组)
bufsize 指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲
stdin, stdout, stderr 分别表示程序的标准输入、输出、错误句柄
preexec_fn 只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
close_sfs 在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。
shell 同上
cwd 用于设置子进程的当前目录
env 用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。
universal_newlines 不同系统的换行符不同,True -> 同意使用 \n
startupinfo 只在windows下有效,将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
createionflags 同上
import subprocess
ret1 = subprocess.Popen(["mkdir","t1"])
ret2 = subprocess.Popen("mkdir t2", shell=True)

终端输入的命令分为两种:

  1. 输入即可得到输出,如:ifconfig
  2. 输入进行某环境,依赖再输入,如:python
import subprocess

obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)     #在cwd目录下执行命令
import subprocess

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
obj.stdin.write("print(1)\n")
obj.stdin.write("print(2)")
obj.stdin.close() cmd_out = obj.stdout.read()
obj.stdout.close()
cmd_error = obj.stderr.read()
obj.stderr.close() print(cmd_out)
print(cmd_error)
import subprocess

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
obj.stdin.write("print(1)\n")
obj.stdin.write("print(2)") out_error_list = obj.communicate()
print(out_error_list)
import subprocess

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
out_error_list = obj.communicate('print("hello")')
print(out_error_list)

python2 commands模块在python3.x被subprocess取代的更多相关文章

  1. python commands模块在python3.x被subprocess取代

    subprocess 可以执行shell命令的相关模块和函数有: os.systemos.spawnos.popen --废弃popen2.* --废弃commands.* --废弃,3.x中被移除 ...

  2. 函数和常用模块【day06】:subprocess模块(十)

    本节内容 1.概述 2.前言 3.subprocess模块 4.subprocess.Popen() 一.概述 我们在实际的工作中,需要跟操作系统的命令做交互,但我们如何用python去跟操作系统之间 ...

  3. [Python2.x] 利用commands模块执行Linux shell命令

    用Python写运维脚本时,经常需要执行linux shell的命令,Python中的commands模块专门用于调用Linux shell命令,并返回状态和结果,下面是commands模块的3个主要 ...

  4. 模块sys, os, glob, pickle, subprocess常见用法

    参考python常用标准库 http://blog.51cto.com/lizhenliang/1872538 一. sys   1. sys.argv 脚本名1.py, 命令行中执行python 1 ...

  5. 学python2.7简单还是python3.0简单,两者区别

    学python2.7简单还是python3.0简单,谈谈两者区别 1. 使用__future__模块 Python 3.X 引入了一些与Python 2 不兼容的关键字和特性.在Python 2中,可 ...

  6. windows XP上实现python2.7.5和python3.4.3共存

    windows XP上实现python2.7.5和python3.4.3共存过程记录: 1. 首先安装python2.7.5和python3.4.3,两个版本安装顺序不分前后; 2. 检查系统环境变量 ...

  7. python中的commands模块,执行出错:'{' 不是内部或外部命令,也不是可运行的程序 或批处理文件。

    最近发现了python的commands模块,查看了下源码,使用的popen封装的,形成三个函数getstatus(), getoutput(), getstatusoutput() 源码如下: de ...

  8. python中的commands模块

    commands模块用于调用shell命令 有3中方法: commands.getstatus()   返回执行状态 commands.getoutput()   返回执行结果 commands.ge ...

  9. 如何把Python2的代码转换为Python3的代码

    如何把Python2的代码转换为Python3的代码 注: 如果对于python2和python3不熟悉的,可以参考: [整理]总结Python2(Python 2.x版本)和Python3(Pyth ...

随机推荐

  1. 什么是Http无状态?Session、Cookie、Token三者之间的区别

    一.什么是HTTP无状态? 1.1定义: HTTP无状态协议,是指协议对于交互性场景没有记忆能力. 1.2举个例子: 在点击一个纯的html网页,请求获取服务器的html文件资源时,每次http请求都 ...

  2. Array类拓展方法

    var arr=[ {name:'one',sex:'girl',handsome:true}, {name:'two',sex:'girl',handsome:false}, {name:'thr' ...

  3. Kattis - virus【字符串】

    Kattis - virus[字符串] 题意 有一个正常的DNA序列,然后被病毒破坏.病毒可以植入一段DNA序列,这段插入DNA序列是可以删除正常DNA序列中的一个连续片段的. 简单来说就是,给你一段 ...

  4. java命令--jmap命令使用(查找内存泄漏对象)

    转自:https://www.cnblogs.com/kongzhongqijing/articles/3621163.html jdk安装后会自带一些小工具,jmap命令(Java Memory M ...

  5. Spring AOP (事务管理)

    一.声明式事务管理的概括 声明式事务(declarative transaction management)是Spring提供的对程序事务管理的方式之一. Spring的声明式事务顾名思义就是采用声明 ...

  6. GIT使用—创建并使用远程版本库

    远程版本库 (1)创建一个裸版本库 [root@localhost tmp]# git init fluff2 Initialized empty Git repository in /tmp/flu ...

  7. Python3.x:定义一个类并且调用

    Python3.x:定义一个类并且调用 1,定一个类Shrjj(其中有属性:name, jjzt,fbsjj,etf,lof,fjlof): class Shrjj(object): def __in ...

  8. sudo fdisk -l

      施其振 2015/1/31 22:06:26 第一行十大5 施其振 2015/1/31 22:06:39 第一行sda5 施其振 2015/1/31 22:06:49 是你的固态硬盘 施其振 20 ...

  9. uboot向linux传递输出任何log信息的方法

    答案:在bootargs中加入loglevel=8即可(在进入linux的过程中会输出任何log信息)

  10. Oracle——ORA-01031: 权限不足

    报错:ORA-01031: 权限不足 解决方法:给用户admin授予DBA角色 grant dba to admin;