Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 让bash脚本作为单独的进程执行多个程序_Python_Linux_Bash_Scripting - Fatal编程技术网

Python 让bash脚本作为单独的进程执行多个程序

Python 让bash脚本作为单独的进程执行多个程序,python,linux,bash,scripting,Python,Linux,Bash,Scripting,正如标题所示,我如何编写一个bash脚本,将例如3个不同的Python程序作为单独的进程执行?然后,我是否能够访问这些进程中的每一个,以查看终端上正在记录的内容 编辑:再次感谢。我忘了提到我知道追加&,但我不确定如何访问每个进程输出到终端的内容。例如,我可以在不同的选项卡上分别运行所有3个程序,并能够看到输出的内容。您可以在后台运行作业,如下所示: command & 1 1 2 2 3 3 1 2 1 3 2 3 这允许您在一行中启动多个作业,而无需等待前一个作业完成 如果像这样

正如标题所示,我如何编写一个bash脚本,将例如3个不同的Python程序作为单独的进程执行?然后,我是否能够访问这些进程中的每一个,以查看终端上正在记录的内容


编辑:再次感谢。我忘了提到我知道追加
&
,但我不确定如何访问每个进程输出到终端的内容。例如,我可以在不同的选项卡上分别运行所有3个程序,并能够看到输出的内容。

您可以在后台运行作业,如下所示:

command &
1
1
2
2
3
3
1
2
1
3
2
3
这允许您在一行中启动多个作业,而无需等待前一个作业完成

如果像这样启动多个后台作业,它们将共享相同的
stdout
(和
stderr
),这意味着它们的输出可能会交错。例如,以以下脚本为例:

#!/bin/bash
# countup.sh

for i in `seq 3`; do
    echo $i
    sleep 1
done
在后台启动两次:

./countup.sh &
./countup.sh &
您在终端中看到的内容如下所示:

command &
1
1
2
2
3
3
1
2
1
3
2
3
但也可能是这样的:

command &
1
1
2
2
3
3
1
2
1
3
2
3
您可能不希望这样,因为很难确定哪个输出属于哪个作业。解决方案是什么?将每个作业的
stdout
(以及可选的
stderr
)重定向到单独的文件。比如说

command > file &
将仅重定向标准输出

command > file 2>&1 &
在后台运行
命令时,将
命令的
stdout
stderr
重定向到
文件
。对Bash中的重定向有很好的介绍。您可以通过
tail
ing文件查看命令的输出“live”:

tail -f file
我建议您在运行后台作业时使用或使用前面提到的user2676075,以便在您关闭终端会话后让作业继续运行,例如

nohup command1 > file1 2>&1 &
nohup command2 > file2 2>&1 &
nohup command3 > file3 2>&1 &
尝试以下方法:

command1 2>&1 | tee commandlogs/command1.log ;
command2 2>&1 | tee commandlogs/command2.log ; 
command3 2>&1 | tee commandlogs/command3.log
...
然后,您可以在命令运行时跟踪文件。记住,您可以通过在目录中并执行“tail*.log”来跟踪它们

或者,您可以通过以下方式设置脚本,为每个命令生成屏幕:

screen -S CMD1 -d -m command1 ;
screen -S CMD2 -d -m command2 ;
screen -S CMD3 -d -m command3
...
然后稍后使用screen--list和screen-r[屏幕名称]重新连接到它们


享受

另一种选择是使用终端仿真器来运行这三个进程。如果您使用的是X,那么可以使用xterm(或rxvt等)

xterm -e <program1> [arg] ... &
xterm -e <program2> [arg] ... &
xterm -e <program3> [arg] ... &
xterm-e[arg]&
xterm-e[arg]&
xterm-e[arg]&
这取决于你想要什么。这种方法允许您弹出终端窗口,以便实时查看输出。您还可以将其与重定向结合起来保存输出