如何在行和列中剪切python输出

时间:2015-02-24 17:25:35

标签: python string awk

大家好我已经写了以下程序来获取linux进程的输出

import subprocess
def backupOperation():
   p = subprocess.Popen(["ls","-la"], stdout=subprocess.PIPE)
   output, err = p.communicate()
   print(output)

 backupOperation()

如果我打印输出,其输出如下所示

-rw-r--r--.  1 root root  100 Dec 29  2013 .cshrc
 drwx------.  3 root root   24 Dec 21 15:14 .dbus
 drwxr-xr-x.  2 root root    6 Dec 21 15:21 Desktop
 drwxr-xr-x.  2 root root    6 Dec 21 15:21 Documents
 drwxr-xr-x.  2 root root    6 Dec 21 15:21 Down loads
 drwx------.  2 root root   22 Dec 21 17:07 .elinks
 -rw-------.  1 root root   16 Dec 21 15:21 .esd_auth
 drwx------.  2 root root   79 Dec 21 16:42 .gnupg
 -rw-------.  1 root root 1240 Feb 21 20:19 .ICEauthority
 -rw-r--r--.  1 root root 1142 Dec 21 15:15 initial-setup-ks.cfg
 drwx------.  3 root root   18 Dec 21 15:21 .local
 drwxr-xr-x.  4 root root   37 Dec 21 16:53 .mozilla
 drwxr-xr-x.  2 root root    6 Dec 21 15:21 Music
 drwxr-xr-x.  2 root root    6 Dec 21 15:21 Pictures
 drwxr-----.  3 root root   18 Dec 21 15:49 .pki
 -rw-r--r--   1 root root  172 Feb 24 22:44 process.py
 -rw-------.  1 root root   10 Dec 21 17:48 .psql_history
 drwxr-xr-x.  2 root root    6 Dec 21 15:21 Public
 -rw-------.  1 root root 1024 Dec 21 16:43 .rnd
 drwx------   2 root root   24 Feb 22 00:12 .ssh
 drwx------.  3 root root 4096 Dec 21 16:44 ssl-build
 -rw-r--r--.  1 root root  129 Dec 29  2013 .tcshrc
 drwxr-xr-x.  2 root root    6 Dec 21 15:21 Templates
drwxr-xr-x.  2 root root    6 Dec 21 15:21 Videos
-rw-------   1 root root 6994 Feb 24 22:44 .viminfo

所有我想要的是切出输出的第一列,就像我使用awk一样使用awk' {print $ 1}' 这里我想用python做这个,但是我找不到任何合适的字符串函数来做这个。可以用python实现,或者我必须使用shell进行这样的操作。

2 个答案:

答案 0 :(得分:3)

def backupOperation():
   p = subprocess.Popen(["ls","-la"], stdout=subprocess.PIPE, universal_newlines=True)
   output, err = p.communicate()
   print("\n".join([ x.split(None,1)[0] for x in output.splitlines()]))

或实际使用awk将输出汇总到它:

def backupOperation():
   p = subprocess.Popen(["ls","-la"], stdout=subprocess.PIPE)
   p2 = subprocess.Popen(["awk", '{print $1}'], stdin=p.stdout, stdout=subprocess.PIPE, universal_newlines=True)
   p.stdout.close()  
   out,err = p2.communicate()
   print("".join(out))

drwxrwxr-x
drwxrwxr-x
-rw-rw-r--
.......

答案 1 :(得分:1)

for line in output.splitlines():
    print line.split(" ",1)[0]

我不确定除了代码之外还要放什么......这是非常基本的东西