简体   繁体   English

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

[英]How to call a shell script from python code?

How to call a shell script from python code?如何从 python 代码调用 shell 脚本?

The subprocess module will help you out.子流程模块将帮助您。

Blatantly trivial example:公然琐碎的例子:

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

Where test.sh is a simple shell script and 0 is its return value for this run.其中test.sh是一个简单的 shell 脚本, 0是这次运行的返回值。

There are some ways using os.popen() (deprecated) or the whole subprocess module, but this approach有使用一些方法os.popen()不建议使用)或整个subprocess模块,但这种方法

import os
os.system(command)

is one of the easiest.是最简单的之一。

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.sh in the same folder:test.sh在同一文件夹中:

#!/bin/sh
echo $1
echo $2
exit 0

Outputs:输出:

$ python test.py 
param1
param2
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")

Use the subprocess module as mentioned above.使用上面提到的子流程模块。

I use it like this:我像这样使用它:

subprocess.call(["notepad"])

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. 1 - 调用脚本。 You will see output in your terminal.您将在终端中看到输出。 output is a number.输出是一个数字。

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

2 - call and dump execution and error into string. 2 - 调用并将执行和错误转储到字符串中。 You don't see execution in your terminal unless you print(stdout).除非您打印(标准输出),否则您不会在终端中看到执行。 Shell=True as argument in Popen doesn't work for me. 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 子流程

I know this is an old question but I stumbled upon this recently and it ended up misguiding me since the Subprocess API as changed since python 3.5.我知道这是一个老问题,但我最近偶然发现了这个问题,它最终误导了我,因为Subprocess API 自 python 3.5 以来发生了变化。

The new way to execute external scripts is with the run function, which runs the command described by args.执行外部脚本的新方法是使用run函数,它运行 args 描述的命令。 Waits for command to complete, then returns a CompletedProcess instance.等待命令完成,然后返回 CompletedProcess 实例。

import subprocess

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

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=$1
serial=$2
echo "podname=$podname  serial=$serial"

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.如果您的脚本是用一些 .sh 文件或长字符串编写的,那么您可以使用 os.system 模块。 It is fairly simple and easy to call:它相当简单且易于调用:

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.此命令将运行脚本一次,直到完成,并阻塞直到它退出。

Subprocess is good but some people may like scriptine better. Subprocess 很好,但有些人可能更喜欢scriptine Scriptine has more high-level set of methods like shell.call(args) , path.rename(new_name) and path.move(src,dst) . Scriptine 有更高级的方法集,如shell.call(args)path.rename(new_name)path.move(src,dst) Scriptine is based on subprocess and others. 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 包当前默认未安装。

If your shell script file does not have execute permissions, do so in the following way.如果您的 shell 脚本文件没有执行权限,请按以下方式执行。

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

In order to run shell script in python script and to run it from particular path in ubuntu, use below;为了在 python 脚本中运行 shell 脚本并从 ubuntu 中的特定路径运行它,请使用以下内容;

import subprocess

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

print(a)

Where CWD is current working directory CWD 当前工作目录在哪里

Below will not work in Ubuntu;以下在 Ubuntu 中不起作用; here we need to remove 'sh'这里我们需要删除'sh'

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

Using @Manoj-Govindan answer, I found that I could run simple shell scripts from python, but the script I was desperately trying to run would fail with the error使用@Manoj-Govindan 的回答,我发现我可以从 python 运行简单的 shell 脚本,但是我拼命尝试运行的脚本会失败并出现错误

Syntax error: "(" unexpected

I changed the first argument from 'sh' to 'bash', and viola.我将第一个参数从“sh”更改为“bash”,然后是 viola。 Suddenly it executed.突然执行了。

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

Please Try the following codes :请尝试以下代码:

Import Execute 

Execute("zbx_control.sh")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM