所以我尝试从 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: a bytes-like object is required, not 'str']。我搜索了这个错误,这意味着我使用 Popen 存储了字节而不是字符串,我不确定为什么,因为我用 print 命令验证了它是一个字符串。在搜索了如何将 shell 命令通过管道传输到字符串后,我尝试使用 check_output。
from subprocess import check_output
a = check_output('file/path/command')
这给了我一个权限错误,所以我想尽可能使用 Popen 命令。
如何将管道 shell 命令转换为字符串,然后如何正确解析分为行和列的字符串,列之间有空格,行之间有空行?
最佳答案
引用 Aaron Maenpaa的 answer :
You need to decode the bytes object to produce a string:
>>> b"abcde" b'abcde' # utf-8 is used here because it is a very common encoding, but you # need to use the encoding your data is actually in. >>> b"abcde".decode("utf-8") 'abcde'
因此你的代码应该是这样的:
i = 0
a = subprocess.Popen('filepath/command', shell=True, stdout=subprocess.PIPE)
b = a.stdout.read().decode("utf-8") # note the decode method
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: list indices must be integers, not tuple
因为你正在将一个元组传递给列表索引salient_Chars
(假设它是一个列表)。
编辑
请注意,调用 print
内置方法不是检查传递的参数是否为纯字符串类型对象的方法。来自引用答案的 OP:
The communicate() method returns an array of bytes:
>>> command_stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
However, I'd like to work with the output as a normal Python string. So that I could print it like this:
>>> print(command_stdout) -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1 -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2
关于python - 解析命令调用的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39091469/