Python calls shell scripts in a number of ways, and here are three ways to execute a shell command in Python
First Scenario: Os.system
Os.system return the exit status code of the script
Existing shell script 1.sh
<span style= "FONT-SIZE:14PX;" ><span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:12PX;" >#!/bin/shecho "Hello world!!" </span></span></span>
invoking the shell script in Python
<span style= "FONT-SIZE:14PX;" ><span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:12PX;" >import osstatus = Os.system (' sh ~/svnrepos/1.sh ') print Statusprint status>>8</span></span>< /SPAN>
Modify the shell script to return status Code 3 when the script exits
The result of the operation is:
This method returns a 16-bit binary number after the shell script is called, and the low is the signal number that kills the called script, and the exit status code for the script is high.
The result returned is 0 (the result of a 8-bit shift to the right by using a bitwise operation is the high value), which means that the code exits normally.
We can use bitwise arithmetic if we need to return the status code to the script after execution.
Second scenario: Os.popen
This method of invocation is implemented by means of a pipeline, and the function returns a File-like object that contains the contents of the script output (which can be simply interpreted as the output of Echo)
By writing shell script 1.sh to try
Third scenario: Using the Commands module
There are three functions:
1.commands.getstatusoutput (CMD)
Use Os.popen () to execute command cmd, and then return a tuple of two elements (status, result)
CMD is executed in {cmd;} 2>&1, so the return result contains standard output and standard error
2.commands.getoutput (CMD)
Returns only the result of execution, ignoring the return value
3.commands.getstatus (file)
return value
Example:
The above method of invocation according to the actual needs to choose the corresponding way
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Python Learning-Invoking shell scripts