Python3 subprocess output(Python3子进程输出)
问题描述
我想运行 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])
                        这篇关于Python3子进程输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python3子进程输出
				
        
 
            
        基础教程推荐
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
 - 在Python中从Azure BLOB存储中读取文件 2022-01-01
 - 求两个直方图的卷积 2022-01-01
 - 包装空间模型 2022-01-01
 - PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
 - 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
 - PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
 - Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
 - 修改列表中的数据帧不起作用 2022-01-01
 - 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
				
				
				
				