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

时间:2022-12-24 17:29:00

How to call a shell script from python code?

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

9 个解决方案

#1


160  

The subprocess module will help you out.

子过程模块将帮助您。

Blatantly trivial example:

公然微不足道的示例:

>>> import subprocess
>>> subprocess.call(['./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.

测试的地方。sh是一个简单的shell脚本,0是这次运行的返回值。

#2


57  

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

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

import sys, os

os.system(command)

is one of the easiest.

是最简单的一种。

#3


33  

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:

与测试。sh在同一文件夹:

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

Outputs:

输出:

$ python test.py 
param1
param2

#4


13  

import os
import sys

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

假设测试。sh是您希望执行的shell脚本

os.system("sh test.sh")

#5


12  

Use the subprocess module as mentioned above.

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

I use it like this:

我这样使用它:

subprocess.call(["notepad"])

#6


6  

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

我正在运行python 3.5和子进程。

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.

调用并将执行和错误转储到字符串中。除非打印(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 - call script and dump the echo commands of temp.txt in temp_file

3 -调用脚本,在temp_file中转储temp.txt的echo命令

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子进程

#7


2  

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.

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

Two drawbacks of scriptine:

scriptine的两个缺点:

  • Current documentation level would be more comprehensive even though it is sufficient.
  • 目前的文件编制水平将更加全面,即使它已经足够。
  • Unlike subprocess, scriptine package is currently not installed by default.
  • 与子进程不同,scriptine包在默认情况下不安装。

#8


2  

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。系统模块。这是相当简单和容易打电话:

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.

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

#9


-7  

Please Try the following codes :

请尝试以下代码:

Import Execute 

Execute("zbx_control.sh")

#1


160  

The subprocess module will help you out.

子过程模块将帮助您。

Blatantly trivial example:

公然微不足道的示例:

>>> import subprocess
>>> subprocess.call(['./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.

测试的地方。sh是一个简单的shell脚本,0是这次运行的返回值。

#2


57  

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

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

import sys, os

os.system(command)

is one of the easiest.

是最简单的一种。

#3


33  

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:

与测试。sh在同一文件夹:

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

Outputs:

输出:

$ python test.py 
param1
param2

#4


13  

import os
import sys

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

假设测试。sh是您希望执行的shell脚本

os.system("sh test.sh")

#5


12  

Use the subprocess module as mentioned above.

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

I use it like this:

我这样使用它:

subprocess.call(["notepad"])

#6


6  

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

我正在运行python 3.5和子进程。

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.

调用并将执行和错误转储到字符串中。除非打印(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 - call script and dump the echo commands of temp.txt in temp_file

3 -调用脚本,在temp_file中转储temp.txt的echo命令

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子进程

#7


2  

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.

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

Two drawbacks of scriptine:

scriptine的两个缺点:

  • Current documentation level would be more comprehensive even though it is sufficient.
  • 目前的文件编制水平将更加全面,即使它已经足够。
  • Unlike subprocess, scriptine package is currently not installed by default.
  • 与子进程不同,scriptine包在默认情况下不安装。

#8


2  

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。系统模块。这是相当简单和容易打电话:

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.

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

#9


-7  

Please Try the following codes :

请尝试以下代码:

Import Execute 

Execute("zbx_control.sh")