Python-call shell scripts, python-shell scripts
There are many methods for python to call Shell scripts. The following describes how to execute shell commands in python.
Solution 1: OS. system
OS. system returns the exit status code of the script.
An 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>
Call shell scripts 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 running result is:
After the shell script is called, this method returns a 16-bit binary number. The low position is the signal number of the script to be called, and the high position is the exit status code of the script.
The returned results are all 0 (the result obtained by the bitwise operation is the high value after the 8-bit shift to the right), indicating that the Code Exits normally.
You can use bitwise operations to obtain the status code returned after the script is executed.
Solution 2: OS. popen
This call method is implemented through pipelines. The function returns a file-like object with the content output by the script (which can be simply understood as the echo output content)
Through the shell script 1. sh to try
Solution 3: Use the commands Module
There are three functions:
1. commands. getstatusoutput (cmd)
Run the command cmd using OS. popen () and then return the tuples (status, result) of the two elements)
The cmd execution method is {cmd;} 2> & 1, so that the returned results contain standard output and standard errors.
2. commands. getoutput (cmd)
Only the execution results are returned, and the returned values are ignored.
3. commands. getstatus (file)
Return Value
Example:
The above call method selects the corresponding method based on actual needs
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.