【发布时间】:2016-08-23 02:37:38
【问题描述】:
所以我试图从 python 执行一个 shell 命令,然后将它存储在一个数组中或直接解析管道 shell 命令。
我通过 subprocess 命令管道传输 shell 数据,并使用 print 语句验证了输出,它工作得很好。
a = subprocess.Popen('filepath/command', shell=True, stdout=subprocess.PIPE)
b = a.stdout.read()
print(b)
现在,我正在尝试从未知数量的行和 6 列中解析出数据。由于 b 应该是一个长字符串,因此我尝试解析字符串并将显着字符存储到另一个数组中以供使用,但是我想分析数据。
i = 0
a = subprocess.Popen('filepath/command', shell=True, stdout=subprocess.PIPE)
b = a.stdout.read()
for line in b.split("\n\n"): #to scan each row with a blank line separating each row
salient_Chars[i, 0] = line.split(" ")[3] #stores the third set of characters and stops at the next blank space
salient_Chars2[i, 0] = line.split(" ")[4] #stores the fourth set of characters and stops at the next blank space
i = i + 1
我收到一个错误 [TypeError: 需要一个类似字节的对象,而不是 'str']。我搜索了这个错误,这意味着我使用 Popen 存储了字节而不是字符串,我不知道为什么,因为我用 print 命令验证了它是一个字符串。在搜索如何将 shell 命令通过管道传输到字符串后,我尝试使用 check_output。
from subprocess import check_output
a = check_output('file/path/command')
这给了我一个权限错误,所以我想尽可能使用 Popen 命令。
如何将管道 shell 命令转换为字符串,然后如何正确解析一个字符串,该字符串分为行和列,列之间有空格,行之间有空行?
【问题讨论】:
-
因为我用 print 命令验证了它是一个字符串 嗯,这不是验证它的一个字符串的方法......显然它不是 字符串类型的对象,否则不会引发该错误。
-
你不能在
str上拆分bytes,使用b.split(b'\n\n')和line.split(b' ') -
如果您向我提供预期的输出,我可以帮助您解决问题的第二部分
-
预期输出就像您引用的 command_stdout 答案一样。 -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1。想象一下,这条线可以是未知数量的行和 6 列。每行由一个空行分隔
标签: python string subprocess stdout popen