Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get stdout and stderr from a tmux session?

I am writing a sample python program in linux system. I am using tmux to create a session and execute another script within the tmux-session. I would like to get the stdout and stderr out of the tmux session to the parent script but that somehow does not work.

Code snippet:

cmd = "tmux new-session -d -s 'test' '/my_dir/fibonacci.py __name:=fibonacci_0'"

proc = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)

(stdout, stderr) = proc.communicate()

print(stderr)

I have came across answers to use show-buffer and pipe-pane. But that did not help. Maybe I need to modify the tmux command itself.

like image 594
soupso Avatar asked Feb 28 '18 14:02

soupso


People also ask

How do you split a tmux session?

ctrl + b + % to make a vertical split. ctrl + b + " to make a Horizontal split. ctrl + b + left arrow to move to the left pane. ctrl + b + " to make a Horizontal split.

How do I run a command in tmux?

Get started with tmux To start using tmux, type tmux on your terminal. This command launches a tmux server, creates a default session (number 0) with a single window, and attaches to it. You can detach from your tmux session by pressing Ctrl+B then D.


2 Answers

Thank you for your support. After digging a bit, I came up with a workaround. I am just adding it here for someone with similar needs.

What I have done is created a named pipe, redirect the output of tmux session to named pipe and then finally read from it.

# this attach if a session exists or creates one, then exits from the session
call("tmux new-session -A -s test \; detach", shell=True)

# to avoid conflict, remove existing named pipe and then create named pipe
call("rm -f /tmp/mypipe && mkfifo /tmp/mypipe && tmux pipe-pane -t test -o 'cat > /tmp/mypipe'", shell=True)

# feed the pipe to the stdout and stderr
poc = Popen(['cat', '/tmp/mypipe'], stdout=PIPE, stderr=PIPE)

# finally execute the command in tmux session
Popen(['tmux', 'send-keys', '-t', '/my_dir/fibonacci.py', 'C-m'])
(stdout, stderr) = proc.communicate()
print(stderr)

Hope this is helpful.

like image 133
soupso Avatar answered Sep 24 '22 13:09

soupso


TLDR: tmux is like sandboxed cmd, you can't get in the session and reach sdtout or stderr

tmux creates a dispatched process. stdout and stderr is tmux would be the text messages that tmux provies, not the commands you run in a tmux session. So you can't get your commands' output from a dispatched process. In order to get the stdout and stderr, you have to change how fibonacci.py dumps text. Python logging framework can help you in this situation. You can write all stdout to stdout.txt and get content of that file.

like image 42
Ramazan Polat Avatar answered Sep 25 '22 13:09

Ramazan Polat