1、使用python内置commands模块执行shellhtml
commands对Python的os.popen()进行了封装,使用SHELL命令字符串做为其参数,返回命令的结果数据以及命令执行的状态;python
该命令目前已经废弃,被subprocess所替代;shell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
# coding=utf-8
'''
Created on 2013年11月22日
@author: crazyant.net
'''
import
commands
import
pprint
def
cmd_exe(cmd_String):
print
"will exe cmd,cmd:"
+
cmd_String
return
commands.getstatusoutput(cmd_String)
if
__name__
=
=
"__main__"
:
pprint.pprint(cmd_exe(
"ls -la"
))
|
2、使用python最新的subprocess模块执行shell服务器
Python目前已经废弃了os.system,os.spawn*,os.popen*,popen2.*,commands.*来执行其余语言的命令,subprocesss是被推荐的方法;学习
subprocess容许你能建立不少子进程,建立的时候能指定子进程和子进程的输入、输出、错误输出管道,执行后能获取输出结果和执行状态。google
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
# coding=utf-8
'''
Created on 2013年11月22日
@author: crazyant.net
'''
import
shlex
import
datetime
import
subprocess
import
time
def
execute_command(cmdstring, cwd
=
None
, timeout
=
None
, shell
=
False
):
"""执行一个SHELL命令
封装了subprocess的Popen方法, 支持超时判断,支持读取stdout和stderr
参数:
cwd: 运行命令时更改路径,若是被设定,子进程会直接先更改当前路径到cwd
timeout: 超时时间,秒,支持小数,精度0.1秒
shell: 是否经过shell运行
Returns: return_code
Raises: Exception: 执行超时
"""
if
shell:
cmdstring_list
=
cmdstring
else
:
cmdstring_list
=
shlex.split(cmdstring)
if
timeout:
end_time
=
datetime.datetime.now()
+
datetime.timedelta(seconds
=
timeout)
#没有指定标准输出和错误输出的管道,所以会打印到屏幕上;
sub
=
subprocess.Popen(cmdstring_list, cwd
=
cwd, stdin
=
subprocess.PIPE,shell
=
shell,bufsize
=
4096
)
#subprocess.poll()方法:检查子进程是否结束了,若是结束了,设定并返回码,放在subprocess.returncode变量中
while
sub.poll()
is
None
:
time.sleep(
0.1
)
if
timeout:
if
end_time <
=
datetime.datetime.now():
raise
Exception(
"Timeout:%s"
%
cmdstring)
return
str
(sub.returncode)
if
__name__
=
=
"__main__"
:
print
execute_command(
"ls"
)
|
也能够在Popen中指定stdin和stdout为一个变量,这样就能直接接收该输出变量值。spa
总结.net
在python中执行SHELL有时候也是很必须的,好比使用Python的线程机制启动不一样的shell进程,目前subprocess是Python官方推荐的方法,其支持的功能也是最多的,推荐你们使用。线程
好了,以上就是这篇文章的所有内容了,但愿本文的内容对你们的学习或者工做能带来必定的帮助,若是有疑问你们能够留言交流。code
原文连接:http://www.crazyant.net/1319.html