gpt4 book ai didi

shell - 逐行读取 python 的 shell 输出

转载 作者:行者123 更新时间:2023-12-04 16:16:47 25 4
gpt4 key购买 nike

我需要从 python 脚本中读取一个 shell 命令输出并用每一行填充一个列表:

问题:
如果我将命令输出保存为变量,循环循环会逐个字符地读取它

#!/usr/bin/python
import subprocess

CMD = "ls -la"
output = subprocess.check_output(CMD, shell=True)
list = []
for line in output:
list.append(line)
print list

错误输出:
['t', 'o', 't', 'a', 'l', ' ', '5',...]

解决方法:
作为一种解决方法,我将命令输出定向到一个文件,并从那里逐行读取:
#!/usr/bin/python
import subprocess

CMD = "ls -la > tmp"
subprocess.call(CMD, shell=True)
list = []
f = open("tmp", "r")
for line in f:
list.append(line)
print list

好输出
['total 52\n', 'drwxrwxr-x 3 ajn ajn 4096 mars 11 17:52 .\n',...]

问题:
如何使用第一种方法(无文件操作,全部在程序内)与第二种方法的结果?

最佳答案

我不是真正的 python 人,但这应该对你有用,而且看起来更清晰:

import subprocess
cmd = ["ls", "-la"]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in proc.stdout.readlines():
print line

关于shell - 逐行读取 python 的 shell 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28993712/

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