本身这个脚本没有什么作用,纯粹是觉得好玩。

执行下面这个命令,我想得到最后一列的数据,其实就是ls的结果

gentoo-pjq / # ls -lh /
total 65K
drwxr-xr-x   2 root root 4.0K 2009-11-11 21:56 bin
drwxr-xr-x   4 root root 1.0K 2009-10-31 16:10 boot
drwxr-xr-x  15 root root 3.9K 2009-11-15 10:33 dev
drwxr-xr-x  94 root root 4.0K 2009-11-15 10:33 etc
drwxr-xr-x  10 root root 4.0K 2009-09-24 20:28 home
drwxr-xr-x  11 root root 4.0K 2009-11-15 00:19 lib
drwx------   2 root root  16K 2009-09-24 19:27 lost+found
drwxr-xr-x  14 root root 4.0K 2009-11-15 10:33 media
drwxr-xr-x   4 root root 4.0K 2008-04-24 03:48 mnt
drwxr-xr-x  18 root root 4.0K 2009-11-15 00:18 opt
dr-xr-xr-x 139 root root    0 2009-11-15 18:32 proc
drwx------  44 root root 4.0K 2009-11-15 11:07 root
drwxr-xr-x   2 root root 4.0K 2009-11-15 00:19 sbin
drwxr-xr-x  12 root root    0 2009-11-15 18:32 sys
drwxrwxrwt   9 root root 4.0K 2009-11-15 15:01 tmp
drwxr-xr-x  16 root root 4.0K 2009-09-26 18:49 usr
drwxr-xr-x  15 root root 4.0K 2009-10-17 19:26 var

要达到这个结果用Python要怎么实现呢:

def exec_shell(command):
    """
    Execute the shell command and return the result.
    """
    pipe=os.popen(command)
    text=pipe.read()
    pipe.close()
    return text

li= str(exec_shell('ls / -lh')).split("\n")
print "\n".join(["%s" %(str(a).split()[7]) for a in li if (lambda args:len(str(a).split()))(a)==8])

运行结果:
bin
boot
dev
etc
home
lib
lost+found
media
mnt
opt
proc
root
sbin
sys
tmp
usr
var

如果改成这样,就可以加上序号了:
print “\n”.join([“%s:%s” %(li.index(a),str(a).split()[7]) for a in li if (lambda args:len(str(a).split()))(a)==8])
1:bin
2:boot
3:dev
4:etc
5:home
6:lib
7:lost+found
8:media
9:mnt
10:opt
11:proc
12:root
13:sbin
14:sys
15:tmp
16:usr
17:var

Python 字符切割

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.