首页 > 解决方案 > 使用 python 运行 bash 脚本

问题描述

我编写了 python 脚本来运行 bash 脚本,它使用以下行运行它:

result = subprocess.Popen(['./test.sh %s %s %s' %(input_file, output_file, master_name)], shell = True)

if result != 0:
    print("Sh*t hits the fan at some point")
    return
else:
    print("Moving further")

现在当 bash 脚本失败时我遇到了麻烦,python 不会继续做它正在做的事情,它只会结束。我怎样才能让它在 bash 失败后继续运行 python 脚本?

标签: pythonbash

解决方案


你忘了communicate. 除了你return,当 bash 脚本失败时,难怪 python “停止”。

from subprocess import Popen, PIPE

p = Popen(..., stdout=PIPE, stderr=PIPE)
output, error = p.communicate()
if p.returncode != 0: 
   print("Sh*t hits the fan at some point %d %s %s" % (p.returncode, output, error))
print("Movign further")

推荐阅读