gpt4 book ai didi

python - 如何从 python 脚本中打破 bash for 循环?

转载 作者:行者123 更新时间:2023-12-01 22:52:23 33 4
gpt4 key购买 nike

我有一个 for 循环,它迭代地运行 python 脚本。 python 脚本中有一个条件,如果满足,则无需继续运行 python 脚本甚至 for 循环。例如:

#Bash Script
for i in {1..15}; do
echo "Pre Outside ${i}"
python minimal_test.py $i
echo "Post Outside ${i}"
done

#Python script
import sys
import subprocess
k = int(sys.argv[1])
end_bash = False

if k == 7:
end_bash = True
print("Inside " + str(k))
if end_bash:
bashCommand = "break"
process = subprocess.Popen(bashCommand, stdout=subprocess.PIPE)

当 bash 脚本中的循环 i == 6 然后是 7 时,程序应该打印:

PreOutside 6
PreInside 6
PostOutside 6
Pre Outside 7
Pre Inside 7 #The program must end here

但是,我收到以下错误并且程序继续运行

File "/software/software/Python/3.9.5-GCCcore-10.3.0/lib/python3.9/subprocess.py", line 1821, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'break'

有没有办法告诉 bash 从 python 脚本内部结束 for 循环?

最佳答案

让您的 Python 脚本因错误而退出。那么shell脚本就变成了

for i in {1..15}; do
python minimal_test.py "$i" || break
done

换句话说,您的 Python 脚本应该 sys.exit(1) 向 shell(或任何调用实用程序)发出错误信号。具体数字由您决定;任何非零数字都是故障代码。 (范围是 0-255,即无符号 char。)

在子进程中运行 break 是没有意义的;您正在启动一个新的 Bash 实例,该实例独立于运行循环的实例,其中 break 当然不会做任何有用的事情,实际上只是孤立的语法错误。

关于python - 如何从 python 脚本中打破 bash for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74059240/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com