sou*_*pso 7 python linux subprocess tmux
我正在 linux 系统中编写一个示例 python 程序。我正在使用tmux创建一个会话并在 tmux-session 中执行另一个脚本。我想从 tmux 会话中获取 stdout 和 stderr 到父脚本,但不知何故不起作用。
代码片段:
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)
Run Code Online (Sandbox Code Playgroud)
我遇到了使用show-buffer和pipe-pane 的答案。但这并没有帮助。也许我需要修改 tmux 命令本身。
感谢您的支持。经过一番挖掘后,我想出了一个解决方法。我只是在这里为有类似需求的人添加它。
我所做的是创建一个命名管道,将 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)
Run Code Online (Sandbox Code Playgroud)
希望这有帮助。
TLDR:tmux 就像沙盒 cmd,您无法进入会话并访问 sdtout 或 stderr
tmux 创建一个调度进程。tmux 中的 stdout 和 stderr 将是 tmux 提供的文本消息,而不是您在 tmux 会话中运行的命令。因此您无法从调度的进程中获取命令的输出。为了获取 stdout 和 stderr,您必须更改 fibonacci.py 转储文本的方式。Python 日志框架可以在这种情况下为您提供帮助。您可以将所有 stdout 写入 stdout.txt 并获取该文件的内容。
归档时间: |
|
查看次数: |
5221 次 |
最近记录: |