如何将命令行输入解析为单独的命令、stdin、stdout和stderr?正则表达式:如何匹配到字符串a或字符串b?

2024-10-01 04:55:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要解析以以下格式运行命令的日志文件:

cmd options < stdin > stdout 2>> stderr

有些命令不使用stdin;有些不使用标准输出

我可以很容易地分开命令;我在写正则表达式时遇到了麻烦,它可以给我其他的部分

我知道如何匹配到单个字符串:

How to match "anything up until this sequence of characters" in a regular expression?

在字符串a或字符串b之前,我不知道如何匹配

也就是说,我希望匹配选项直到<;或>;或2>&燃气轮机;发生

像这样的尝试是行不通的

import re

test = "cmd test1 test2 -c test3 < infile > outfile 2>> err"

optRegex = '.+?(?=>|<|(2>>))'
optRegex = re.compile(optRegex)

stdoutRegex = '>+?(?=>|<|(2>>))'
stdoutRegex = re.compile(stdoutRegex)

# get options
result = optRegex.search(test)
options = result.group()
rest = test[len(options):]
options = options.rstrip()

# get stdout
result = stdoutRegex.search(rest)
stdout = result.group()
rest = rest[len(stdout):]
stdout = stdout.rstrip()


print(options)
print(stdout)
print(rest)

输出:

cmd test1 test2 -c test3
>
 infile > outfile 2>> err

事后看来,使用循环和扫描开始字符和结束字符可能更容易,但我对regex解决方案很好奇

谢谢


Tags: 字符串test命令gtrecmdreststdin