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


当前回答

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

scriptine的两个缺点:

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

其他回答

我正在运行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"

为了在python脚本中运行shell脚本,并从ubuntu中的特定路径运行它,请使用下面的方法;

import subprocess

a= subprocess.call(['./dnstest.sh'], cwd = "/home/test") 

print(a)

CWD是当前工作目录

下图将不能在Ubuntu中运行;这里我们需要删除'sh'

subprocess.call(['sh' ,'./dnstest.sh'], cwd = "/home/test")

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

显而易见的小例子:

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

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

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

import os
os.system(command)

是最简单的方法之一。