1. os.system

In [32]: run = os.system("date")
Thu Jan 28 09:41:25 CST 2016
In [33]: run
Out[33]: 0

只能得到返回值,无法得到输出。

2. os.popen

In [35]: run = os.popen("date")
In [36]: run.read
Out[36]: <function read>
In [37]: run.read()
Out[37]: 'Thu Jan 28 09:43:14 CST 2016\n'

只能得到输出,无法得到返回值。

3. commands模块

In [39]: run = commands.getstatusoutput("date")
In [40]: run
Out[40]: (0, 'Thu Jan 28 09:44:44 CST 2016')

返回一个数组。

4. subprocess模块

4.1 call

In [42]: run = subprocess.call(["uname","-a"], shell=True)
Linux
In [43]: run
Out[43]: 0

直接输出结果,将返回值赋值给变量,类似os.system

4.2 Popen

In [44]: run = subprocess.Popen("uname -a", shell=True,stdout=subprocess.PIPE)
In [48]: run.stdout.read()
Out[48]: 'Linux test-sun207 3.10.0-229.el7.x86_64 #1 SMP Fri Mar 6 11:36:42 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux\n'
In [49]: run.wait()
Out[49]: 0

注意: 当执行命令的参数或者返回中包含了中文文字,那么建议使用subprocess,如果使用os.popen则会出现错误。

5. sh模块

安装:pip install sh

In [62]: from sh import ifconfig
In [63]: run = sh.ifconfig
In [64]: run
Out[64]: <Command '/usr/sbin/ifconfig'>
In [65]: run()
Out[65]:
ens32: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.1.207 netmask 255.255.255.0 broadcast 192.168.1.255
inet6 fe80::20c:29ff:fe71:888 prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:71:08:88 txqueuelen 1000 (Ethernet)
RX packets 95617464 bytes 8518940518 (7.9 GiB)
RX errors 0 dropped 7078520 overruns 0 frame 0
TX packets 1175268 bytes 172715015 (164.7 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 0 (Local Loopback)
RX packets 191 bytes 58512 (57.1 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 191 bytes 58512 (57.1 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
In [67]: run.bake()
Out[67]: <Command '/usr/sbin/ifconfig'>
In [68]: run('lo')
Out[68]:
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 0 (Local Loopback)
RX packets 191 bytes 58512 (57.1 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 191 bytes 58512 (57.1 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

执行脚本:

import sh
run = sh.Command("/home/amoffat/run.sh") # Absolute path
run()

多个参数:

from sh import tar
tar("cvf", "/tmp/test.tar", "/my/home/directory")

关键字参数:

# resolves to "curl http://duckduckgo.com/ -o page.html --silent"
curl("http://duckduckgo.com/", o="page.html", silent=True)
# or if you prefer not to use keyword arguments, this does the same thing:
curl("http://duckduckgo.com/", "-o", "page.html", "--silent")
# resolves to "adduser amoffat --system --shell=/bin/bash --no-create-home"
adduser("amoffat", system=True, shell="/bin/bash", no_create_home=True)
# or
adduser("amoffat", "--system", "--shell", "/bin/bash", "--no-create-home")

返回值:

output = ls("/")
print(output.exit_code) # should be 0
#捕获异常:
try: print(ls("/some/non-existant/folder"))
except ErrorReturnCode_2:
print("folder doesn't exist!")
create_the_folder()
except ErrorReturnCode:
print("unknown error")
exit(1)

###:

In [92]: sh.ls(sh.glob('*.txt'))
Out[92]: requirements.txt

tail:

In [93]: for line in sh.tail("-f", "requirements.txt", _iter=True):
....: print line #实现其他更好玩的功能
....:
requests==2.9.0
six==1.10.0
slip==0.4.0
#callback实现:
def process_output(line):
print(line)
p = tail("-f", "/var/log/some_log_file.log", _out=process_output)
p.wait()

py执行系统命令的更多相关文章

  1. Pyhton 学习总结 20 :执行系统命令

    在Python中执行系统命令有os.system().os.popen().commands.getstatusoutput().subprocess.Popen等     1.os.system() ...

  2. Python执行系统命令的方法

    Python中执行系统命令常见方法有两种: 两者均需 import os (1) os.system # 仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息 system(command) ...

  3. Python中执行系统命令常见的几种方法--转载

    Python中执行系统命令常见的几种方法 Python中执行系统命令常见的几种方法有: (1)os.system # 仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息 # 如果再命令行下执 ...

  4. Python执行系统命令:使用subprocess的Popen函数

    使用subprocess的Popen函数执行系统命令 参考: http://blog.sina.com.cn/s/blog_8f01450601017dlr.html http://blog.csdn ...

  5. 转 Python执行系统命令的方法

    传送门 Python执行系统命令的方法 http://www.linux-field.com/?p=15 Python中执行系统命令常见方法有两种: 两者均需 import os (1) os.sys ...

  6. python 执行系统命令模块比较

    python 执行系统命令模块比较 1.os.system模块 仅仅在子终端运行命令,返回状态码,0为成功,其他为失败,但是不返回执行结果 如果再命令行下执行,结果直接打印出来 >>> ...

  7. java中执行系统命令

    java程序中执行系统命令猛击下面的链接看看你就知道怎么用了 http://blog.csdn.net/a19881029/article/details/8063758 http://wuhongy ...

  8. Java 执行系统命令

    在Java中执行系统命令,主要是使用ProcessBuilder和Runtime.getRuntime().exec().而在这里主要是介绍两种方法的使用. 使用情景是在linux系统中,使用menc ...

  9. Python执行系统命令的方法 os.system(),os.popen(),commands

    os.popen():用python执行shell的命令,并且返回了结果,括号中是写shell命令 Python执行系统命令的方法: https://my.oschina.net/renwofei42 ...

随机推荐

  1. spring Bean的三种注入方式

    1.构造函数注入: 构造函数的注入方式分为很多种 (1)普通构造函数,空参数的构造函数 <bean id="exampleBean" class="examples ...

  2. 窗口信息获取器 Spy4Win v0.20b 中文绿色版

    软件名称:窗口信息获取器 Spy4Win v0.20b 中文绿色版软件类别:国产软件运行环境:Windows XP软件语言:简体中文授权方式:免费版软件大小:1.67 MB软件等级:整理时间:2012 ...

  3. curl 命令使用总结

    curl 查看网页源码 curl www.sina.com 保存页面 -o curl -o [文件名] www.sina.com 直接在curl命令后加上网址,就可以看到网页源码. 如果要把这个网页保 ...

  4. Java swing 如何将一个按钮放置到弹出框框的任意位置?(Absolute layout 布局的使用)

    准备: Absolute layout 绝对布局,绝对布局中控件的可以在任意位置放置 如何制作下面那种样子的 弹出框? ---------------------------------------- ...

  5. Java并发编程:深入剖析ThreadLocal(转载)

    Java并发编程:深入剖析ThreadLocal(转载) 原文链接:Java并发编程:深入剖析ThreadLocal 想必很多朋友对ThreadLocal并不陌生,今天我们就来一起探讨下ThreadL ...

  6. java登录密码效验

    密码校验需求: 1) 密码控制只能输入字母.数字.特殊符号(~!@#$%^&*()_+[]{}|\;:'",./<>?)2) 长度 6-16 位,必须包括字母.数字.特殊 ...

  7. 重读The C programming Lanuage 笔记一:类型转换

    首先说自动类型转换: 当一个运算符的几个操作数类型不同时,就需要吧他们转换位某种共同的类型.一般来说,自动转换把“较低”的类型转换为”较高“的类型.运算结果为较高的类型 以下是不严格的规则: 首先,如 ...

  8. Sub Lime Text

    Sub Lime Text License -– BEGIN LICENSE -– Andrew Weber Single User License EA7E-855605 813A03DD 5E4A ...

  9. php中的curl常用例子

    1.基本请求 <?php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.baidu.com"); ...

  10. DPDK l2fwd 浅注

    l2fwd是DPDK中的非常经典的例子.二层转发模型. 就是在相邻的网卡接口间互相传递报文. 网口0和网口1之间报文互传. 网口2和网口3之间报文互传. ............ 运行参数 . 在目录 ...