python执行shell命令

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

1 os.system

可以返回运行shell命令状态,同时会在终端输出运行结果

例如ipython中运行如下命令,返回运行状态status

os.system('cat /etc/passwdqc.conf')

min=disabled,24,11,8,7max=40passphrase=3match=4similar=deny

random=47enforce=everyone

retry=3Out[6]: 0

2 os.popen()

可以返回运行结果

popen(command [, mode='r'[, bufsize]]) ->pipe

Open a pipe to/froma command returning a file object.

运行返回结果

In [20]: output = os.popen('cat /PRoc/cpuinfo')

In [21]: lineLen =[]

In [22]:forlineinoutput.readlines():

lineLen.append(len(line))

....:

In [23]: line

line lineLen

In [23]: lineLen

Out[23]:

[14,25,

...

3 如何同时返回结果和运行状态,commands模块:

#String form: <module 'commands' from '/usr/lib64/python2.7/commands.pyc'>File: /usr/lib64/python2.7/commands.py

Docstring:

Execute shell commands via os.popen()andreturnstatus, output.

Interface summary:importcommands

outtext=commands.getoutput(cmd)

(exitstatus, outtext)=commands.getstatusoutput(cmd)

outtext= commands.getstatus(file)#returns output of "ls -ld file"A trailing newlineisremovedfromthe output string.

Encapsulates the basicOperation:

pipe= os.popen('{'+ cmd +'; } 2>&1','r')

text=pipe.read()

sts= pipe.close()

commands示例如下:

In [24]: (status, output) = commands.getstatusoutput('cat /proc/cpuinfo')

In [25]: status

Out[25]: 0

In [26]: len(output)

Out[26]: 3859

4 使用模块subprocess

ipython 中运行"?subprocess"可以发现subprocess是python用来替换os.popen()等管道操作命令的新模块

A more real-world example would look like this:try:

retcode= call("mycmd"+"myarg", shell=True)ifretcode <0:print>>sys.stderr,"Child was terminated by signal", -retcodeelse:print>>sys.stderr,"Child returned", retcodeexceptOSError, e:print>>sys.stderr,"Execution failed:", e

相对于上面几种方式,subprocess便于控制和监控进程运行结果,subprocess提供多种函数便于应对父进程对子进程不同要求:

4.1.1 subprocess.call()

父进程父进程等待子进程完成,返回exit code

4.1.2 subprocess.check_call()

父进程等待子进程完成,返回0,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性,可用try...except...来检查

4.1.3 subprocess.check_output()

父进程等待子进程完成

返回子进程向标准输出的输出结果

检查退出信息,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性和output属性,output属性为标准输出的输出结果,可用try...except...来检查

例如:

In [32]: out = subprocess.call("ls -l", shell=True)

total42244

-rw-rw-r--. 1 *** *** 366 May 26 09:10 ChangeLog

4.2.1

上面三个函数都是源于Popen()函数的wapper(封装),如果需要更加个性化应用,那么就需要使用popen()函数

Popen对象创建后,主程序不会自动等待子进程完成。我们必须调用对象的wait()方法,父进程才会等待(也就是阻塞block)

[wenwt@localhost syntax]$ rm subprocess.pyc

[wenwt@localhost syntax]$ python process.py

parent process

[wenwt@localhost syntax]$ PING www.google.com (173.194.219.99) 56(84) bytes of data.^C

[wenwt@localhost syntax]$--- www.google.com ping statistics ---

5 packets transmitted, 0 received, 100% packet loss, time 3999ms

加上wait方法:

[wenwt@localhost syntax]$ python process.py

PING www.google.com (173.194.219.103) 56(84) bytes of data.--- www.google.com ping statistics ---

5 packets transmitted, 0 received, 100%packet loss, time 3999ms

parent process

参考文章:Python标准库06 子进程 (subprocess包)

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航