2015-02-24 53 views
1

嗨蟒蛇輸出所有我寫了下面的程序採取的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做這個,但是我沒有找到任何合適的字符串函數來做這件事。可以用蟒蛇或我必須使用shell進行此類操作。

回答

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-- 
....... 
+0

以上代碼未在運行 – thinkingmonster 2015-02-24 18:10:29

+0

什麼不正確運行意味着什麼? – 2015-02-24 18:11:37

+1

o我不知道你可以使用None作爲第一個參數的分割......多數民衆贊成酷:P – 2015-02-24 18:14:54

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

林不知道放什麼其他不僅僅是代碼...這是一件很基本的

+0

請向我提供解釋我如何使用它來切割5列中有不同的子列 – thinkingmonster 2015-02-24 17:57:56

+0

你不......你有一個文本塊...你沒有列或行... – 2015-02-24 18:14:03