因此,我尝试从 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 命令转换为字符串,然后如何正确解析分为行和列的字符串,列之间有空格,行之间有空行?