Python3子进程输出

2022-01-18 00:00:00 python python-3.x subprocess

问题描述

我想运行 Linux 字数统计实用程序 wc 来确定/var/log/syslog 中当前的行数,以便我可以检测到它正在增长.我尝试了各种测试,当我从 wc 中得到结果时,它包括行数和命令(例如,var/log/syslog).

I want to run the Linux word count utility wc to determine the number of lines currently in the /var/log/syslog, so that I can detect that it's growing. I've tried various test, and while I get the results back from wc, it includes both the line count as well as the command (e.g., var/log/syslog).

所以它正在返回:第1338章但我只想要行数,所以我想去掉/var/log/syslog 部分,只保留 1338.

So it's returning: 1338 /var/log/syslog But I only want the line count, so I want to strip off the /var/log/syslog portion, and just keep 1338.

我尝试将它从字节串转换为字符串,然后剥离结果,但没有任何乐趣.转换为字符串和剥离、解码等的相同故事 - 都无法产生我正在寻找的输出.

I have tried converting it to string from bytestring, and then stripping the result, but no joy. Same story for converting to string and stripping, decoding, etc - all fail to produce the output I'm looking for.

这些是我得到的一些示例,系统日志中有 1338 行:

These are some examples of what I get, with 1338 lines in syslog:

  • b'1338/var/log/syslog '
  • 1338/var/log/syslog
  • b'1338 /var/log/syslog '
  • 1338 /var/log/syslog

这是我编写的一些测试代码,试图破解这个问题,但没有解决方案:

Here's some test code I've written to try and crack this nut, but no solution:

import subprocess

#check_output returns byte string
stdoutdata = subprocess.check_output("wc --lines /var/log/syslog", shell=True)
print("2A stdoutdata: " + str(stdoutdata))
stdoutdata = stdoutdata.decode("utf-8")
print("2B stdoutdata: " + str(stdoutdata))    
stdoutdata=stdoutdata.strip()
print("2C stdoutdata: " + str(stdoutdata))    

由此产生的输出是:

  • 2A 标准输出数据:b'1338/var/log/syslog '

  • 2A stdoutdata: b'1338 /var/log/syslog '

2B 标准输出数据:1338/var/log/syslog

2B stdoutdata: 1338 /var/log/syslog

2C 标准输出数据:1338/var/log/syslog

2C stdoutdata: 1338 /var/log/syslog

2D 标准输出数据:1338/var/log/syslog

2D stdoutdata: 1338 /var/log/syslog


解决方案

我建议你使用 subprocess.getoutput() 因为它完全符合你的要求——在 shell 中运行命令并获取它的 字符串输出(相对于 字节串输出).然后你可以 在空白处分割 并从返回的字符串列表.

I suggest that you use subprocess.getoutput() as it does exactly what you want—run a command in a shell and get its string output (as opposed to byte string output). Then you can split on whitespace and grab the first element from the returned list of strings.

试试这个:

import subprocess
stdoutdata = subprocess.getoutput("wc --lines /var/log/syslog")
print("stdoutdata: " + stdoutdata.split()[0])

相关文章