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

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

上面这些命令,可以使用subprocess完美的实现,而且具有丰富的功能:

call:   python3.5以下才有, python3.5及以上变成run方法

执行命令,返回状态码

>>> a = subprocess.call('whoami')
huangxm-pc\huangxm
>>> print(a)
0

执行一个带参数的命令

>>> subprocess.call('ls -l')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>

报错了,对于这种可以加上shell=True, 表示完全当成shell命令执行

>>> subprocess.call('ls -l', shell=True)
total 48
drwxr-xr-x 5 huanghao huanghao 4096 Mar 12 18:42 day7
drwxrwxrwx 2 huanghao huanghao 4096 Oct 19 22:42 Desktop

check_call

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

>>> subprocess.check_call('cat /etc/passwd | grep root', shell=True)
root:x:0:0:root:/root:/bin/bash
0
>>> subprocess.check_call('cat /etc/passwddd | grep root', shell=True) #执行失败,抛出异常
cat: /etc/passwddd: No such file or directory
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.4/subprocess.py", line 557, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command 'cat /etc/passwddd | grep root' returned non-zero exit status 1

check_output

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

 

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与createionflags只在windows下有效
    将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
a = subprocess.Popen('ipconfig', shell=True)
print(a) 执行结果
<subprocess.Popen object at 0x0000000002809240><subprocess.Popen object at 0x0000000002809240>

命令成功执行了,但是没有获得到结果,怎么获得结果呢?

a = subprocess.Popen('ipconfig', shell=True, stdout=subprocess.PIPE).stdout.read()
print(str(a, 'gbk')) #winodws中文是gbk

有时候我们并不是只这样运行命令,而是需要进入一些目录去执行一些命令,比如我们要在D盘建立一个文件夹:

a = subprocess.Popen('mkdir aaaaa', shell=True, cwd='C:/')

执行之后,到C盘看一下,有没有一个aaaaa的文件夹。

再来看一个复杂点的:

第一步:先在D盘根目录建立一个文件aa.py,内容如下:

def add():
x = input('input x:').strip()
print('\n')
y = input('input y:').strip()
print('\n')
print('the result is ', int(x)+int(y)) if __name__ == "__main__":
add()

第二步:执行下面的代码

obj = subprocess.Popen('python3 D:/aa.py', shell=True, cwd='c:/python34', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write(b'1\n')
obj.stdin.write(b'2\n')
obj.stdin.close()
cmd_out = str(obj.stdout.read(), 'gbk')
obj.stdout.close()
print(cmd_out)

第三步:查看执行结果

input x:

input y:

the result is  3

在提示要输入的时候,我们根本就没有在键盘上输入,因为stdin.write已经帮我们完成了输入。 然后程序通过stdout.read()将结果读取出来。如果程序执行中发生错误,还可以能过obj.stderr.read()获取错误信息。

python(6)-执行shell命令的更多相关文章

  1. python中执行shell命令的几个方法小结(转载)

    转载:http://www.jb51.net/article/55327.htm python中执行shell命令的几个方法小结 投稿:junjie 字体:[增加 减小] 类型:转载 时间:2014- ...

  2. python中执行shell命令的几个方法小结

    原文 http://www.jb51.net/article/55327.htm 最近有个需求就是页面上执行shell命令,第一想到的就是os.system, os.system('cat /proc ...

  3. C++/Php/Python 语言执行shell命令

    编程中经常需要在程序中使用shell命令来简化程序,这里记录一下. 1. C++ 执行shell命令 #include <iostream> #include <string> ...

  4. python中执行shell命令行read结果

    +++++++++++++++++++++++++++++ python执行shell命令1 os.system 可以返回运行shell命令状态,同时会在终端输出运行结果 例如 ipython中运行如 ...

  5. 「Python」6种python中执行shell命令方法

    用Python调用Shell命令有如下几种方式: 第一种: os.system("The command you want"). 这个调用相当直接,且是同步进行的,程序需要阻塞并等 ...

  6. python中执行shell命令的几个方法

    1.os.system() a=os.system("df -hT | awk 'NR==3{print $(NF-1)}'") 该命令会在页面上打印输出结果,但变量不会保留结果, ...

  7. python批量执行shell命令

    [root@master ~]# cat a.py #!/usr/bin/python # -*- coding:UTF- -*- import subprocess def fun(): subpr ...

  8. python中执行shell命令

    查看输出结果 import os output = os.popen('cat 6018_gap_5_predict/solusion2/solusion2_0-1.txt | wc -l') pri ...

  9. python中执行shell的两种方法总结

    这篇文章主要介绍了python中执行shell的两种方法,有两种方法可以在Python中执行SHELL程序,方法一是使用Python的commands包,方法二则是使用subprocess包,这两个包 ...

随机推荐

  1. Ubuntu 安装 Sun JDK

    1. 下载    Oracle网站下载JDK7     http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1 ...

  2. 一条scan查询把HBase集群干趴下

    最近在给公司搭建CDH集群,在测试集群性能时,写了一条简单的scan查询语句竟然把hbase集群的所有regionserver干趴下了.这让我云里雾里的飘飘然. 背景介绍 CDH集群,2台主节点.3台 ...

  3. Java缓存学习之三:CDN缓存机制

    CDN是什么? 关于CDN是什么,此前网友详细介绍过. CDN是Content Delivery Network的简称,即"内容分发网络"的意思.一般我们所说的CDN加速,一般是指 ...

  4. vim MiniBufExplorer 插件

    MiniBufExplorer安装好久了,但一直没怎么使用过. 今天查了下资料,作为一个备份. 当你只编辑一个buffer的时候MiniBufExplorer派不上用场, 当 你打开第二个buffer ...

  5. Java设计模式系列之动态代理模式(转载)

    代理设计模式 定义:为其他对象提供一种代理以控制对这个对象的访问. 动态代理使用 java动态代理机制以巧妙的方式实现了代理模式的设计理念. 代理模式示例代码 public interface Sub ...

  6. 【C语言】-循环的嵌套

    循环的嵌套:当在一个循环语句中嵌入另一个循环时,成为循环的嵌套. 循环嵌套的形式: (1)for语句中嵌入for语句: for ( ) { for ( ) { ... } } (2)for语句嵌入wh ...

  7. thymeleaf比较符号问题

    比较器与平等: 值表达可以是>.<.> =.< =符号,像往常一样,也是= =和!=操作符可以用来检查平等,但是>.<.> =.< =不能用,要用gt ...

  8. Science上发表的超赞聚类算法(转)

    作者(Alex Rodriguez, Alessandro Laio)提出了一种很简洁优美的聚类算法, 可以识别各种形状的类簇, 并且其超参数很容易确定. 算法思想 该算法的假设是类簇的中心由一些局部 ...

  9. shell脚本的入参

    shell脚本参数可以任意多,但只有前9个可以被访问,使用shift命令可以改变这个限制.参数从第一个开始,在第九个结束.$0 程序名字$n 第n个参数值,n=1..9 $* 所有命令行参数$@    ...

  10. skyline TerraExplorer fly设置相对路径的方法

    软件环境:TerraExplorer Pro(以下简称TEP)6.5 在TEP中,对于本地(非网络)文件路径,默认都是绝对路径,在移动数据时非常麻烦,以下是本人总结出一些设置相对路径的规则 假设fly ...