How to pull the output of the most recent terminal command?

岁酱吖の 提交于 2019-12-24 19:44:04

问题


I'm building a CLI that, when run, requires the output of the most recently executed bash command. Is it possible to pull this output without recomputing the command?

For example, let's say I run python main.py and receive this error:

File "main.py", line 41
messages_list.insert(0, { "author" : "dummy_author0", "message" : " " } )
                                                                        ^
IndentationError: unindent does not match any outer indentation level

I'd like to then run a command that automatically pulls this error message and does something with it, without re-running python main.py.


I'm thinking that running command1; command2 could provide a way for command2 to pull the output of command1 since the execution of both in sequence might be treated as a single process, but I'm not sure how.


回答1:


The shell (and terminals) by themselves will not do this for you.

I'd wrap the command in a shell-script which calls the script command, e.g.,

  • create a temporary filename (system-dependent, but for example with mktemp),
  • use that temporary file as the output for script, rather than the default typescript.
  • in the command passed to script, echo the exit-code since script will hide that from you
  • in the shell-script, filter out carriage-returns, etc., e.g., with script2log, and
  • the last line of the filtered output would have the exit-code. Use that for the exit-code of the shell-script

For your CLI program, make the shell-script accept a parameter which tells the shell-script where to write the output of the command. Likely that is another temporary file, avoiding the problem of redirecting the output of the command to a file or pipe, making the output no longer a terminal.

If you're using the Linux variant of script, it could be something like this:

#!/bin/sh
# $1 = command
# $2 = output
code=0
tempfile=$(mktemp)
trap "rm -f \$tempfile; exit \$code" EXIT INT QUIT HUP
script -q -c "$1; echo \$?" $tempfile
script2log <$tempfile >$2
code=$(tail -n 1 $tempfile)



回答2:


For the compile time error like you are stating i would assume not. Because when there is a formatting issue like that the python file is never run in the first place. My only idea would be to create another python project that runs the first python project using a bash command and collects the output from sterror

if you want to collect the runtime errors you could try putting the whole thing inside a try catch and doing something with it, ex:

try:
    myfuncode()
except:
    print "Unexpected error:", sys.exc_info()[0]
    #do stuff here


来源:https://stackoverflow.com/questions/49013526/how-to-pull-the-output-of-the-most-recent-terminal-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!