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


当前回答

有一些方法使用os.popen()(已弃用)或整个子进程模块,但这种方法

import os
os.system(command)

是最简单的方法之一。

其他回答

import os
import sys

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

os.system("sh test.sh")

如上所述,使用子流程模块。

我是这样使用的:

subprocess.call(["notepad"])

我正在运行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子流程

Subprocess很好,但有些人可能更喜欢scriptine。Scriptine有更高级的方法集,如shell.call(args), path.rename(new_name)和path.move(src,dst)。Scriptine基于子流程和其他。

scriptine的两个缺点:

当前的文档水平将更加全面,即使它是足够的。 与subprocess不同,scriptine包目前默认不安装。

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

Syntax error: "(" unexpected

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

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