AntonGepting / tmux-interface-rs

Rust language library for communication with TMUX via CLI
MIT License
51 stars 5 forks source link

Is it possible to extract terminal contents? #3

Closed jgarvin closed 3 years ago

jgarvin commented 3 years ago

I have been looking for a way to programmatically scrape what is currently displayed in a terminal, and it occurred to me that if I could work with screen or tmux rather than a particular graphical emulator that it would offer me more flexibility. I'm not an existing tmux user though so I'm not familiar with all the vocabulary that's in the docs. It looks like most of the API is for letting you choose between windows and modes -- buffers looked like a promising area but it also seems to be oriented around switching tmux in and out of "buffer mode". Is it possible to do scraping?

AntonGepting commented 3 years ago

Hello, thank you for your interest and sorry for late reply.

I am not sure if the ways suggested below are really suitable for your purposes. These suggestions are written not using API of the library, but since the library functions are practically wrappers around tmux commands, you can try to translate it in rust code. I hope these approaches allow you to come near the solution of your problem.

  1. Using buffers (capture-pane, show-buffer, save-buffer ...)
#!/bin/bash

# create new session and do not attach to it right now
tmux new-session -s session1 -d

# send some command to the current pane in this session
tmux send-keys -t session1 "ls -la" Enter

# capture screen, creating new named buffer
tmux capture-pane -b buffer1 -S -

# once you have it in buffer you can:

# show captured lines, stdout
tmux show-buffer -b buffer1

# save into the file
tmux save-buffer -b buffer1 buffer.log

# release buffer
tmux delete-buffer -b buffer1

# close session
tmux kill-session -t session1
  1. Using pipes (pipe-pane)
#!/bin/bash

# create new session and do not attach to it right now
tmux new-session -s session2 -d

# prepare output redirection to other command
pipe-pane -O -t session2 "cat >> pipe.log"

# send some command to the current pane in this session
tmux send-keys -t session2 "ls -la" Enter

# close session
tmux kill-session -t session2
  1. With a high degree of probability there are another ways to solve this problem by other methods. Takes probably a little bit more time to research.

You can take a look at the tmux manual (man tmux) for additional information about tmux commands and flags used in scripts.

If you still have questions or suggestions... please feel free to communicate and leave comments.

jgarvin commented 3 years ago

Thanks for the very thorough response! I didn't realize it's that easy to get data out.