大家好,我已经写了下面的程序来获取 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 '{print $1}' 这样使用 awk 来剪切输出的第一列 在这里,我想使用 python 来执行此操作,但我没有找到任何合适的字符串函数来执行此操作。这可以使用 python 来实现,还是我必须使用 shell 来进行此类操作。
最佳答案
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--
.......
关于python - 如何在行和列中剪切 python 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28702293/