【发布时间】:2019-05-07 12:41:57
【问题描述】:
我有一个shell 命令,它解析特定内容并提供所需的输出。我需要在 python 中实现这个,但是 shell 命令有一个换行符"\n",当通过 python 命令运行时它不会被执行。
在输出日志中的许多行中,所需的行看起来像 - configurationFile=/app/log/conf/the_jvm_name.4021.logback.xml
我只需要上面的 the_jvm_name。语法将始终相同。 shell 命令工作正常。
Shell 命令 -
ps -ef | grep 12345 | tr " " "\n" | grep logback.configurationFile | awk -F"/" '{print $NF}'| cut -d. -f1
Python(转义所有必需的双引号) -
import subprocess
pid_arr = "12345"
sh_command = "ps -ef | grep "+pid_arr+" | tr \" \" \"\n\" | grep configurationFile | awk -F \"/\" '{print $NF}' | cut -d. -f1"
outpt = subprocess.Popen(sh_command , shell=True,stdout=subprocess.PIPE).communicate()[0].decode('utf-8').strip()
使用 python,我没有得到想要的输出。它只是打印命令中的配置文件。 我在这里想念什么。还有其他更好的方法来获取这些详细信息吗?
【问题讨论】:
-
最简单的方法是使用python分割和解析
subprocess的输出,而不是依赖grep+tr+grep+awk -
我已经尝试过了,但它会中断输出。我们可以使用正则表达式吗?
标签: python shell subprocess