如何使用 Python 从文本中提取一列?

ANV*_*ANV 5 python

我是python编程的新手。通过在互联网上搜索 python 文档来编写此脚本。

任何人都可以帮助我仅将第二列作为“ps aux”命令的输出(即仅 PID 列)。

#script to print the processid
import os
import commands
out=commands.getoutput('ps aux') # to get the process listing in out
#print out
#print out[2] #print only second column from out
print out[:2] 

output of "print out" statement
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0   5728  1068 ?        Ss   Oct13   0:07 /sbin/init
root         2  0.0  0.0      0     0 ?        S<   Oct13   0:00 [kthreadd]
root         3  0.0  0.0      0     0 ?        S<   Oct13   0:00 [migration/0]
root         4  0.0  0.0      0     0 ?        S<   Oct13   0:11 [ksoftirqd/0]
root         5  0.0  0.0      0     0 ?        S<   Oct13   0:00 [watchdog/0]
root         6  0.0  0.0      0     0 ?        S<   Oct13   0:00 [migration/1]
Run Code Online (Sandbox Code Playgroud)

提前致谢

Ray*_*ger 3

使用split()and splitlines()(将字符串转换为行列表,并将行列表转换为列列表,然后您可以根据需要对其进行索引):

>>> for line in out.splitlines():
...     fields = line.split()
...     if len(fields) >= 2:
...         print fields[1]


PID
1
2
3
4
5
6
Run Code Online (Sandbox Code Playgroud)