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

时间:2021-11-16 08:42:11

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

    1、os.system()

Python中关于os.system的描述:

>>> import os
>>> help(os.system)
system(command) -> exit_status
Execute the command (a string) in a subshell.

os.system()的命令执行是在子shell中执行,返回的是执行的退出状态码

>>> import os
>>> returnCode = os.system('adb devices')
List of devices attached
>>> print returnCode
0
>>> print open('C://temp.txt', 'r').readlines() ['List of devices attached \n', '\n']

2、os.popen()

Python官方文档关于os.popen的描述

<SPAN style="FONT-FAMILY: 宋体; FONT-SIZE: 15px">os.popen(command[, mode[, bufsize]])
Open a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'. The bufsize argument has the same meaning as the corresponding argument to the built-in open() function. The exit status of the command (encoded in the format specified for wait()) is available as the return value of the close() method of the file object, except that when the exit status is zero (termination without errors), None is returned. Availability: Unix, Windows. Deprecated since version 2.6: This function is obsolete. Use the subprocess module. Check especially the Replacing Older Functions with the subprocess Module section. Changed in version 2.0: This function worked unreliably under Windows in earlier versions of Python. This was due to the use of the _popen() function from the libraries provided with Windows. Newer versions of Python do not use the broken implementation from the Windows libraries.</SPAN>

使用管道执行命令,“返回值”是一个打开的文件对象,该文件对象里面是系统命令的“输出”。对其进行读取 read() 的操作可以看到执行的输出。

>>> import os
>>> returnCode = os.popen('adb devices')
>>> print returnCode
<open file 'adb devices', mode 'r' at 0x00B99C80>
>>> print returnCode.read()
List of devices attached

3、commands.getstatusoutput()

可以获得到返回值和输出,非常好用。

(status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
print status, output
>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'

4、subprocess.Popen

Python官方文档关于subprocess的描述

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several other, older modules and functions, such as: 

os.system
os.spawn*
os.popen*
popen2.*

subprocess.call代替os.system

>>> import subprocess
>>> returnCode = subprocess.call('adb devices')
List of devices attached >>> print returnCode
0
>>>

subprocess.check_output代替os.popen

>>> import subprocess
>>> returnCode = subprocess.check_output('adb devices')
>>> print returnCode
List of devices attached

subprocess.Popen使用

stdout

>>> import subprocess
>>> sp = subprocess.Popen('adb devices', shell=True, stdout=subprocess.PIPE)
>>> print sp
<subprocess.Popen object at 0x00BB68F0>
>>> print sp.stdout.read()
List of devices attached
#!/usr/bin/env python
# -*- coding: utf-8 -*- a = int(raw_input())
b = int(raw_input()) print 'a + b = ', a+b
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
p =subprocess.Popen('python C://plus.py', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
p.stdin.write('4\n')
p.stdin.write('5\n')
print p.stdout.readline()

PS:

1、test.py中,'python C://plus.py'里的python是必须的,参见:http://blog.csdn.net/jq0123/article/details/7448589

2、test.py中,p.stdin.write('4\n')里的“\n”是必须的