【问题标题】:Running bash script with python [duplicate]用python运行bash脚本[重复]
【发布时间】:2019-06-24 19:22:25
【问题描述】:

我编写了 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 不会继续做它正在做的事情,它只会结束。如何使 python 脚本在 bash 失败后继续运行?

【问题讨论】:

  • 你试过try/except

标签: python bash


【解决方案1】:

您忘记了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")

【讨论】:

  • 它的作用是什么?
  • 获取错误的堆栈跟踪。但我意识到你只是return 当returncode != 0...难怪它“刚刚结束”
  • 正如文档已经告诉您的那样,如果您可以使用为您处理这些细节的高级函数之一,请不要使用裸 Popen。在这种情况下,如果子进程失败,check_call 或 run(..., check=True) 将引发异常。
猜你喜欢
  • 2019-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-11
  • 2018-03-14
  • 2014-12-01
  • 2013-03-14
  • 1970-01-01
相关资源
最近更新 更多