如何从python代码调用shell脚本?


当前回答

请尝试以下代码:

Import Execute 

Execute("zbx_control.sh")

其他回答

请尝试以下代码:

Import Execute 

Execute("zbx_control.sh")

我知道这是一个老问题,但我最近偶然发现了这个问题,它最终误导了我,因为Subprocess API自python 3.5以来发生了变化。

执行外部脚本的新方法是使用run函数,它运行args所描述的命令。等待命令完成,然后返回一个CompletedProcess实例。

import subprocess

subprocess.run(['./test.sh'])

使用@Manoj-Govindan的答案,我发现我可以从python运行简单的shell脚本,但我拼命想要运行的脚本会因为错误而失败

Syntax error: "(" unexpected

我把第一个参数从'sh'改成了'bash',还有viola!突然,它执行了。

subprocess.call(['bash', './test.sh'])
import os
import sys

假设test.sh是您想要执行的shell脚本

os.system("sh test.sh")

子流程模块将帮助您解决这个问题。

显而易见的小例子:

>>> import subprocess
>>> subprocess.call(['sh', './test.sh']) # Thanks @Jim Dennis for suggesting the []
0 
>>> 

其中test.sh是一个简单的shell脚本,0是这次运行的返回值。