gpt4 book ai didi

python - 如何从 subprocess 命令获取输出作为 python 中的列表?

转载 作者:太空宇宙 更新时间:2023-11-04 03:22:04 24 4
gpt4 key购买 nike

我正在尝试使用 python 脚本检索有关我的 perforce 客户端的一些信息。我只想获取与服务器地址、客户端根等相关的信息,如下所示:

ping_string = subprocess.Popen(['p4', 'info','ls'], stdout=subprocess.PIPE ).communicate()[0]
print ping_string

所以我得到的输出是:

User name: hello
Client name: My_machine
Client host: XYZ
Current directory: c:\
Peer address: 1.2...
Client address: 1.102....
Server address: abcd
Server root: D:\scc\data

但是因为我想检索服务器地址、客户端地址等,所以我希望输出以列表的形式出现。所以,请建议我如何获得列表类型的输出。

最佳答案

使用 check_output简化了获取命令输出的过程,因此您可以:

out = subprocess.check_output(cmd)

lines = out.splitlines()

请注意,每一行都将包含尾随换行符。

或者如果您想要冒号后的数据:

lines = [l.split(':', 1)[1].strip() for l in out.splitlines() 
if ':' in l]

l.split(':', 1)[1] 取冒号后的任何内容。.strip() 移除周围的空格。if ':' in l 是针对不包含冒号的行的保护。

关于python - 如何从 subprocess 命令获取输出作为 python 中的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34383666/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com