1

When I do something like:

$ echo "print \"test\"" | python

I want:

Python 2.7.15rc1 (default, Apr 15 2018, 21:51:34) 
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more 
information.
>>> print "test"
test

Instead of:

test

Is there some way to capture all the prompts in the stdout?

4
  • I don't think this is related to the capturing of "all" output - it's a matter of running python interactively - which you can do by adding the -i option: echo "print \"test\"" | python -i Aug 21, 2018 at 2:11
  • How about script command?
    – unxnut
    Aug 21, 2018 at 2:18
  • @steeldriver I just tried it and it's still missing the ">>> print ..." input line. Is there something more generic to work with other interactive cli programs, not just python?
    – skim99
    Aug 21, 2018 at 2:25
  • Well - there's expect Aug 21, 2018 at 2:52

1 Answer 1

3

You can combine all the suggestions made in comments like so, with a here string mixed in:

$ script -c 'python -i <<< "print \"test\""'
Script started, file is typescript
Python 2.7.5 (default, Jul 13 2018, 13:06:57)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> test
>>>
Script done, file is typescript

Which will log the above into a file called, typescript:

$ cat typescript
Script started on Tue 21 Aug 2018 12:19:50 AM EDT
Python 2.7.5 (default, Jul 13 2018, 13:06:57)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> test
>>>

Script done on Tue 21 Aug 2018 12:19:50 AM EDT

The above method works like so:

  • script -c'...'- runs the commands in single quotes inscriptand logs the output to the filetypescript`
  • python -i <<< "...." - runs Python in interactive mode, passing a command, "...." in as a here string
  • "print \"test\"" - command to run as a here string

typescript with escape sequences

If you find that your resulting typescript file contains escape sequences such as:

ESC[34mRPMsESC[39;49mESC[0m
ESC[34mRPMs_fpmESC[39;49mESC[0m
ESC[34mansibleESC[39;49mESC[0m

You can use less -R or less -r to view these:

$ less -R somefile
RPMs
RPMs_fpm
ansible

References

2
  • Thanks, "script" looks like what I want. However, the typescript output file has some weird characters. Examples are "\u001b]0;" "\u001b[00m" "u001b[01;34m". Any suggestions on how to clean it up?
    – skim99
    Aug 21, 2018 at 18:12
  • That's output based on your $PROMPT being colorized. Those are escape characters which make define what colors to show your shell's prompt. Try viewing the file with less -R, this will properly display these escape sequences.
    – slm
    Aug 21, 2018 at 18:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .