我正在linux系统中编写一个示例python程序。我在用tmux https://linux.die.net/man/1/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)
我找到了可以使用的答案显示缓冲区 https://stackoverflow.com/a/24720356/1800026 and 管板 https://stackoverflow.com/a/43014752/1800026。但这并没有帮助。也许我需要修改 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)
希望这有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)