如何从tmux会话中获取stdout和stderr?

问题描述 投票:3回答:2

我正在linux系统中编写一个示例python程序。我正在使用tmux创建一个会话并在tmux-session中执行另一个脚本。我想将stdout和stderr从tmux会话中移出到父脚本但是不知何故不起作用。

代码段:

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)

我遇到过使用show-bufferpipe-pane的答案。但这没有帮助。也许我需要修改tmux命令本身。

python linux subprocess tmux
2个回答
2
投票

TLDR:tmux就像沙盒cmd,你无法进入会话并达到sdtout或stderr

tmux创建一个调度进程。 stdout和stderr是tmux将是tmux提供的文本消息,而不是您在tmux会话中运行的命令。因此,您无法从调度的进程获取命令的输出。为了获取stdout和stderr,您必须更改fibonacci.py转储文本的方式。 Python日志框架可以在这种情况下帮助您。您可以将所有stdout写入stdout.txt并获取该文件的内容。


0
投票

感谢您的支持。挖了一下之后,我想出了一个解决方法。我只是在这里为有类似需求的人添加它。

我所做的是创建一个命名管道,将tmux会话的输出重定向到命名管道,然后最终从中读取。

# 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)

希望这是有帮助的。

© www.soinside.com 2019 - 2024. All rights reserved.