python执行linux命令有两种方法:
在此以Linux常用的ls命令为例:
方法一:使用os模块
1
2
3
|
shell
# python
>>
import
os
>> os.system(
'ls -l'
)
|
执行结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
drwxr-xr-x 2 root root 4096 2012-03-12 bin
drwxr-xr-x 4 root root 1024 2011-10-31 boot
drwxr-xr-x 6 root root 4096 2011-11-22 data
drwxr-xr-x 12 root root 3620 01-11 16:01 dev
drwxr-xr-x 93 root root 12288 01-17 04:02 etc
drwxr-xr-x 16 root root 4096 10-18 18:53 home
drwxr-xr-x 11 root root 4096 2012-03-12 lib
drwxr-xr-x 8 root root 4096 2012-01-20 lib64
drwx------ 2 root root 16384 2011-10-31 lost+found
drwxr-xr-x 2 root root 4096 2010-01-27 media
drwxr-xr-x 2 root root 0 01-11 16:00 misc
drwxr-xr-x 2 root root 4096 2011-12-02 mnt
drwxr-xr-x 2 root root 0 01-11 16:00 net
drwxr-xr-x 12 root root 4096 2011-11-22 new
drwxr-xr-x 2 root root 4096 2010-01-27 opt
dr-xr-xr-x 168 root root 0 01-11 15:59 proc
drwxr-x--- 6 root root 4096 11-06 11:30 root
drwxr-xr-x 2 root root 12288 2012-03-31 sbin
drwxr-xr-x 2 root root 4096 2011-10-31 selinux
drwxr-xr-x 2 root root 4096 2010-01-27 srv
drwxr-xr-x 11 root root 0 01-11 15:59 sys
drwxrwxrwt 4 root root 20480 01-18 04:02 tmp
drwxr-xr-x 16 root root 4096 07-25 16:34 usr
drwxr-xr-x 21 root root 4096 2011-11-02 var
|
方法二:使用subprocess模块
1
2
3
4
5
|
shell
# python
>>
import
subprocess
>> subprocess.call(
'ls -l'
.
split
())
|
执行结果是相同的。
ps:开发中最常用的方法是os模块方法。