问题:如何从python代码调用Shell脚本?
How to call a shell script from python code?
回答 0
该子模块将帮助你。
显而易见的例子:
>>> import subprocess
>>> subprocess.call(['./test.sh']) # Thanks @Jim Dennis for suggesting the []
0
>>>
其中test.sh
是一个简单的shell脚本,0
它是此运行的返回值。
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.
回答 1
有一些使用os.popen()
(不推荐使用)或整个subprocess
模块的方法,但是这种方法
import os
os.system(command)
是最简单的之一。
There are some ways using os.popen()
(deprecated) or the whole subprocess
module, but this approach
import os
os.system(command)
is one of the easiest.
回答 2
如果要将一些参数传递给Shell脚本,可以使用shlex.split()方法:
import subprocess
import shlex
subprocess.call(shlex.split('./test.sh param1 param2'))
与test.sh
在同一文件夹:
#!/bin/sh
echo $1
echo $2
exit 0
输出:
$ python test.py
param1
param2
In case you want to pass some parameters to your shell script, you can use the method shlex.split():
import subprocess
import shlex
subprocess.call(shlex.split('./test.sh param1 param2'))
with test.sh
in the same folder:
#!/bin/sh
echo $1
echo $2
exit 0
Outputs:
$ python test.py
param1
param2
回答 3
import os
import sys
假设test.sh是您要执行的shell脚本
os.system("sh test.sh")
import os
import sys
Assuming test.sh is the shell script that you would want to execute
os.system("sh test.sh")
回答 4
如上所述,使用子流程模块。
我这样使用它:
subprocess.call(["notepad"])
Use the subprocess module as mentioned above.
I use it like this:
subprocess.call(["notepad"])
回答 5
我正在运行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子流程
I’m running python 3.5 and subprocess.call([‘./test.sh’]) doesn’t work for me.
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.
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.
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
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
回答 6
子流程模块是启动子流程的好模块。您可以使用它来调用shell命令,如下所示:
subprocess.call(["ls","-l"]);
#basic syntax
#subprocess.call(args, *)
您可以在此处查看其文档。
如果您的脚本是用.sh文件或长字符串编写的,则可以使用os.system模块。调用起来非常简单容易:
import os
os.system("your command here")
# or
os.system('sh file.sh')
该命令将运行脚本一次,直到完成,然后阻塞直到退出。
Subprocess module is a good module to launch subprocesses.
You can use it to call shell commands as this:
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:
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.
回答 7
如果脚本有多个参数
#!/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"
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.
podname=xyz serial=1234
0
Below is the test.sh shell script.
#!/bin/bash
podname=$1
serial=$2
echo "podname=$podname serial=$serial"
回答 8
Subprocess is good but some people may like scriptine better. 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 subprocess and others.
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.
回答 9
我知道这是一个老问题,但是最近我偶然发现了这个问题,由于Subprocess API自python 3.5以来发生了变化,最终导致了我的误解。
执行外部脚本的新方法是使用run
函数,该函数运行args描述的命令。等待命令完成,然后返回CompletedProcess实例。
import subprocess
subprocess.run(['./test.sh'])
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.
The new way to execute external scripts is with the run
function, which runs the command described by args. Waits for command to complete, then returns a CompletedProcess instance.
import subprocess
subprocess.run(['./test.sh'])
回答 10
如果您的Shell脚本文件没有执行权限,请按照以下方式进行操作。
import subprocess
subprocess.run(['/bin/bash', './test.sh'])
If your shell script file does not have execute permissions, do so in the following way.
import subprocess
subprocess.run(['/bin/bash', './test.sh'])
回答 11
请尝试以下代码:
Import Execute
Execute("zbx_control.sh")
Please Try the following codes :
Import Execute
Execute("zbx_control.sh")