Python heredoc 如何用作 Bash 进程替换的输入?

How can Python heredoc be used as input for a Bash process substitution?

我有一个 Python 脚本,它定义了 tmux 的配​​置,然后使用此配置启动 tmux。配置作为 heredoc 存储在 Python 中,我想在执行 Bash tmux 启动命令时在 Bash 进程替换中使用它。

所以,我想做这样的事情:

configuration = \
"""
set -g set-remain-on-exit on
new -s "FULL"
set-option -g prefix C-a
unbind C-b
bind - split-window -v
bind | split-window -h
## colours
set-option -g window-status-current-bg yellow
set-option -g pane-active-border-fg yellow
set -g status-fg black
set -g status-bg '#FEFE0A'
set -g message-fg black
set -g message-bg '#FEFE0A'
set -g message-command-fg black
set -g message-command-bg '#FEFE0A'
set-option -g mode-keys vi
set -g history-limit 5000
## mouse mode
set -g mode-mouse on
set -g mouse-select-pane on
set -g mouse-select-window on
set -g mouse-resize-pane on # resize panes with mouse (drag borders)
## status
set-option -g status-interval 1
set-option -g status-left-length 20
set-option -g status-left ''
set-option -g status-right '%Y-%m-%dT%H%M%S '
## run programs in panes
# split left-right
split-window -h
# split left up
select-pane -t 0
split-window -v
select-pane -t 0
split-window -v
select-pane -t 0
split-window -v
select-pane -t 3
split-window -v
select-pane -t 0
send-keys 'ranger' Enter
select-pane -t 1
send-keys 'clear' Enter
select-pane -t 2
#send-keys 'htop' Enter
select-pane -t 3
send-keys 'elinks http://arxiv.org/list/hep-ph/new' Enter
select-pane -t 4
send-keys 'cmus' Enter
select-pane -t 5
send-keys 'ranger' Enter
select-pane -t 4
set -g set-remain-on-exit off
"""

command = executable + " -f <(echo " + configuration + ") attach"
os.system(command)

我应该更改什么才能使其正常工作?

Python 的 os.system() 是根据 C 的 system() 函数定义的,它通过 /bin/sh -c <the command> 运行给定的命令。即使 /bin/sh 是 bash 的别名,当 bash 启动时 作为 sh,它在 POSIX 中运行模式,并且 POSIX 不提供进程替换(<(<command>))。

看起来最好的办法可能是将配置写入临时文件,然后在命令中指定该文件的名称。如果您可以使用 mktemp 命令,那么它是制作临时文件的理想选择。也许按照这些思路可以做到:

command = "config=`mktemp` && { echo \"" + configuration + "\" > $config; "
        + executable + " -f $config attach; unlink $config; }"

此外,即使您可以使用它,bash 进程替换也是一种 重定向 。如果正在启动的进程,它会影响标准输入(或标准输出),并且不会取代文件名。