python执行linux命令有两种方法:
在此以Linux常用的ls命令为例:
shell# python>> import os>> os.system('ls -l')
执行结果:
drwxr-xr-x 2 root root 4096 2012-03-12 bindrwxr-xr-x 4 root root 1024 2011-10-31 bootdrwxr-xr-x 6 root root 4096 2011-11-22 datadrwxr-xr-x 12 root root 3620 01-11 16:01 devdrwxr-xr-x 93 root root 12288 01-17 04:02 etcdrwxr-xr-x 16 root root 4096 10-18 18:53 homedrwxr-xr-x 11 root root 4096 2012-03-12 libdrwxr-xr-x 8 root root 4096 2012-01-20 lib64drwx------ 2 root root 16384 2011-10-31 lost+founddrwxr-xr-x 2 root root 4096 2010-01-27 mediadrwxr-xr-x 2 root root 0 01-11 16:00 miscdrwxr-xr-x 2 root root 4096 2011-12-02 mntdrwxr-xr-x 2 root root 0 01-11 16:00 netdrwxr-xr-x 12 root root 4096 2011-11-22 newdrwxr-xr-x 2 root root 4096 2010-01-27 optdr-xr-xr-x 168 root root 0 01-11 15:59 procdrwxr-x--- 6 root root 4096 11-06 11:30 rootdrwxr-xr-x 2 root root 12288 2012-03-31 sbindrwxr-xr-x 2 root root 4096 2011-10-31 selinuxdrwxr-xr-x 2 root root 4096 2010-01-27 srvdrwxr-xr-x 11 root root 0 01-11 15:59 sysdrwxrwxrwt 4 root root 20480 01-18 04:02 tmpdrwxr-xr-x 16 root root 4096 07-25 16:34 usrdrwxr-xr-x 21 root root 4096 2011-11-02 var
方法二:使用subprocess模块
shell# python >> import subprocess >> subprocess.call('ls -l'.split())
执行结果是相同的。
ps:开发中最常用的方法是os模块方法。