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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3777301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:41:39  来源:igfitidea点击:

How to call a shell script from python code?

pythonshell

提问by Umesh K

How to call a shell script from python code?

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

采纳答案by Manoj Govindan

The subprocessmodule will help you out.

模块将帮助你。

Blatantly trivial example:

公然琐碎的例子:

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

Where test.shis a simple shell script and 0is its return value for this run.

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

回答by Micha? Niklas

There are some ways using os.popen()(deprecated) or the whole subprocessmodule, but this approach

有一些方法可以使用os.popen()(已弃用)或整个subprocess模块,但是这种方法

import os
os.system(command)

is one of the easiest.

是最简单的之一。

回答by hugo24

Use the subprocess module as mentioned above.

使用上面提到的子流程模块。

I use it like this:

我像这样使用它:

subprocess.call(["notepad"])

回答by Akseli Palén

Subprocess is good but some people may like scriptinebetter. Scriptine has more high-level set of methods like shell.call(args), path.rename(new_name)and path.move(src,dst). Scriptine is based on subprocessand others.

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

Two drawbacks of scriptine:

脚本的两个缺点:

  • Current documentation level would be more comprehensive even though it is sufficient.
  • Unlike subprocess, scriptine package is currently not installed by default.
  • 当前的文档级别会更全面,即使它已经足够了。
  • 与 subprocess 不同,scriptine 包当前默认未安装。

回答by Manas

Please Try the following codes :

请尝试以下代码:

Import Execute 

Execute("zbx_control.sh")

回答by Franck Dernoncourt

In case you want to pass some parameters to your shell script, you can use the method shlex.split():

如果您想将一些参数传递给您的 shell 脚本,您可以使用shlex.split()方法:

import subprocess
import shlex
subprocess.call(shlex.split('./test.sh param1 param2'))

with test.shin the same folder:

test.sh在同一文件夹:

#!/bin/sh
echo 
echo 
exit 0

Outputs:

输出:

$ python test.py 
param1
param2

回答by Srayan Guhathakurta

import os
import sys

Assuming test.sh is the shell script that you would want to execute

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

os.system("sh test.sh")

回答by Ankit Singh

Subprocess module is a good module to launch subprocesses. You can use it to call shell commands as this:

子流程模块是启动子流程的好模块。您可以使用它来调用 shell 命令,如下所示:

subprocess.call(["ls","-l"]);
#basic syntax
#subprocess.call(args, *)

You can see its documentation here.

您可以在此处查看其文档

If you have your script written in some .sh file or a long string, then you can use os.system module. It is fairly simple and easy to call:

如果您的脚本是用一些 .sh 文件或长字符串编写的,那么您可以使用 os.system 模块。它相当简单且易于调用:

import os
os.system("your command here")
# or
os.system('sh file.sh')

This command will run the script once, to completion, and block until it exits.

此命令将运行脚本一次,直到完成,并阻塞直到它退出。

回答by lauralacarra

I'm running python 3.5 and subprocess.call(['./test.sh']) doesn't work for me.

我正在运行 python 3.5 并且 subprocess.call(['./test.sh']) 对我不起作用。

I give you three solutions depends on what you wanna do with the output.

我给你三个解决方案取决于你想用输出做什么。

1 - call script. You will see output in your terminal. output is a number.

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

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

2 - call and dump execution and error into string. You don't see execution in your terminal unless you print(stdout). Shell=True as argument in Popen doesn't work for me.

2 - 调用并将执行和错误转储到字符串中。除非您打印(标准输出),否则您不会在终端中看到执行。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 - call script and dump the echo commands of temp.txt in temp_file

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)

Don't forget to take a look at the doc subprocess

不要忘记查看doc 子流程

回答by Rishi Bansal

In case the script is having multiple arguments

如果脚本有多个参数

#!/usr/bin/python

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

Output will give the status code. If script runs successfully it will give 0 otherwise non-zero integer.

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

podname=xyz  serial=1234
0

Below is the test.sh shell script.

下面是 test.sh shell 脚本。

#!/bin/bash

podname=
serial=
echo "podname=$podname  serial=$serial"