2011-11-23 30 views
2

我有一个小脚本,它着色编译器(maven)输出,所以错误不会被忽略。过程流在EOL之前

#!/bin/sh 
export TEXT_YELLOW=`tput setaf 3` 
export TEXT_RED=`tput setaf 1` 
export RESET_FORMATTING=`tput sgr0` 

mvn $* | sed \ 
-e "s/\(\[WARNING\].*\)/${TEXT_YELLOW}\1${RESET_FORMATTING}/g" \ 
-e "s/\(\[ERROR\].*\)/${TEXT_RED}\1${RESET_FORMATTING}/g" 

问题是一个外壳内的外壳拥有我的编译器(mvn cli:execute-phase)。在屏幕上应该可以看到类似maven2>的命令提示符,然后用户可以输入命令。不幸的是,由于我的脚本,我只看到一个闪烁的光标。只有当我按下回车键时,maven2> prompt-prefix-text弹出。

我的猜测是,sed正在等待EOL,然后在屏幕上打印某些东西。要解决它,我将不得不看看如果流开始字符串maven2>。如果是,则直接打印到终端,否则将其转发到sed。在bash中可能吗?

+0

你不能关闭该功能,并seding输出后启动交互式会话? – choroba

+1

不幸的是我不能。交互式会话由开发人员用来编译特定模块或触发自动化测试。那就是我需要着色的地方 –

回答

1

好的,我找到了一个解决方案。我尝试了很多东西,但最终无法单纯用bash解决问题。所以我写了一个Python脚本,它的工作原理。只需将这个maven输出传递给脚本,如mvn cli:execute-phase | colorize.py。也可以在你的bashrc中写一个别名,这样所有的maven调用都有彩色输出。

#!/usr/bin/python 
# Same as regular mvn command but with colored output. 

import sys, subprocess, os, time 

def colorize(line): 
    red = '\033[1;31m' 
    yellow = '\033[1;33m' 
    endcolor = '\033[1;m' 

    if ("[ERROR]" in line) or ("ERROR" in line) or ("Failures" in line) or ("Errors" in line):   
     print red + line + endcolor,  
    elif ("[WARNING]" in line) or ("WARN" in line): 
     print yellow + line + endcolor, 
    else: 
     print line, 


line="" 
printPrompt = True 
while True: 

    c = sys.stdin.read(1) 

    if not c: 
     # eof 
     break 

    line = line + c 

    if printPrompt: 
     if line.startswith("maven2>"):   
      print "maven2>", 
      sys.stdout.flush() 
      printPrompt = False 
    else: 
     # rewrite the current line to console 
     sys.stdout.write('\r') 
     print line, 
     sys.stdout.flush() 

    if c.endswith("\n"): 
     colorize(line) 
     line = "" 
     printPrompt = True 
1

@mainbrain你蟒蛇的剧本工作,除了罚款“MVN原型:产生”时,提示“为属性定义值‘的groupId’:”被显示。

例如

mvn archetype:generate \ 
    -DarchetypeRepository=repo1.maven.org \ 
    -DarchetypeGroupId=org.codehaus.mojo \ 
    -DarchetypeArtifactId=gwt-maven-plugin \ 
    -DarchetypeVersion=2.4.0