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


当前回答

我正在运行python 3.5, subprocess.call(['./test.sh'])不适合我。

我给出三个解取决于你对输出的处理。

1 -调用脚本。您将在终端中看到输出。输出是一个数字。

import subprocess 
output = subprocess.call(['test.sh'])

2 -调用和转储执行和错误到字符串。除非输出(stdout),否则在终端中看不到执行。Shell=True作为Popen中的参数并不适用于我。

import subprocess
from subprocess import Popen, PIPE

session = subprocess.Popen(['test.sh'], stdout=PIPE, stderr=PIPE)
stdout, stderr = session.communicate()

if stderr:
    raise Exception("Error "+str(stderr))

3 -调用脚本,将temp.txt的echo命令转储到temp_file中

import subprocess
temp_file = open("temp.txt",'w')
subprocess.call([executable], stdout=temp_file)
with open("temp.txt",'r') as file:
    output = file.read()
print(output)

别忘了看一看doc子流程

其他回答

以防脚本有多个参数

#!/usr/bin/python

import subprocess
output = subprocess.call(["./test.sh","xyz","1234"])
print output

输出将给出状态代码。如果脚本成功运行,它将给出0否则非零整数。

podname=xyz  serial=1234
0

下面是test.sh shell脚本。

#!/bin/bash

podname=$1
serial=$2
echo "podname=$podname  serial=$serial"

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

Syntax error: "(" unexpected

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

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

请尝试以下代码:

Import Execute 

Execute("zbx_control.sh")

如果您的shell脚本文件没有执行权限,请按照以下方法执行。

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

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

os.system("sh test.sh")