To execute shell commands in Python and get their results, you can usually use thesubprocess
module. This module allows us to start new processes, connect to their input/output/error pipelines, and get their return codes. Here is a detailed example showing how to use the()
function to execute Shell commands and get their output.
1. Example 1: Execute the ls command using () and get the results
This example will execute thels
command (lists files and folders in the current directory on Unix/Linux/macOS systems) and captures the output and return codes of the command.
import subprocess # Define the commands to be executed command = ['ls', '-l'] # Use the list form, more secure, can avoid shell injection attacks # Execute commands # capture_output=True Parameter indicates capture command output (stdout and stderr) # text=True parameter indicates that the output will be processed as text (Python 3.7+), previous versions used universal_newlines=True result = (command, capture_output=True, text=True) # Get the standard output of the command stdout = # Get the error output of the command (if any) stderr = # Get the return code of the command returncode = # Print results print(f"standard output:\n{stdout}") if stderr: print(f"error output:\n{stderr}") print(f"return code: {returncode}") # take note of:If the command is successfully executed,returncodetypically0;in-0value indicates that an error has occurred
caveat:
(1)safety: This example uses a list of commands rather than strings to avoid shell injection attacks. When commands and arguments are provided as a list, Python passes them directly to the system without interpreting them through the shell, thus reducing security risks.
(2)Text and Bytes:capture_output=True
cap (a poem)text=True
(oruniversal_newlines=True
(in older versions) are combined so that the output is returned as text (strings) instead of bytes. This is convenient for working with text data, but if we need to work with binary data (such as images or video files), we may need to capture the output in bytes.
(3)error handling: By inspectionreturncode
You can determine whether the command was successfully executed. If thereturncode
is not 0, then it may be necessary to use the same method based on thestderr
in the information to diagnose the problem.
(4)Cross-platform compatibility: In this example, thels -l
Commands are specific to Unix/Linux/macOS systems. On Windows systems, we may need to execute different commands (e.g.dir
), and may need to adjust the way the command is invoked (e.g., using theshell=True
(but please note that this increases the security risk).
(5)Performance considerations: Starting external processes frequently may degrade the performance of your program. If possible, try to solve the problem internally in Python, or consider using multithreading/multiprocessing to handle external command calls in parallel.
2. Example 2: Using the () function to execute shell commands
Here is a more detailed code example that shows how to use the Python()
function to execute shell commands (in this case thels -l
), and handles a variety of situations that may arise, including successful execution, command non-existence, and capture of standard and error output.
Note that this example assumes we're running on a Unix/Linux/macOS system, because thels -l
is the command for those systems. If we're on Windows, we may need to replace thedir
command, and may need to adjust theshell
parameter (although it is generally recommended to avoid the use ofshell=True
(to avoid security risks).
import subprocess def run_command(command): """ Executes the given command and returns its output and return code. Parameters. - command: the command to be executed, passed as a list (e.g. ['ls', '-l']) to avoid shell injection. Returns: output: the standard output of the command (if any). - output: The standard output of the command (if any). - error: The error output of the command, if any. - returncode: The return code of the command. """ try: # Execute commands using () # capture_output=True means capture stdout and stderr # text=True means treat output as text (Python 3.7+) result = (command, capture_output=True, text=True, check=True) # If the command executes successfully (no exceptions), return its output and return code return , None, except as e: # Catch CalledProcessError exception if command execution fails (return code non-zero) # and return the error output, standard output (if any) and return code return None, , except Exception as e: # Catch other possible exceptions (although probably less common in this simple example) return None, f"An unexpected error occurred: {e}", None # Define the commands to be executed command = ['ls', '-l'] # Execute commands and get results output, error, returncode = run_command(command) # Print the appropriate information based on the returned results if output: print("Standard Output:") print(output) if error: print("Error output:") print(error) if returncode is not None: print(f"return code: {returncode}") if returncode == 0: print("Command successfully executed.") else: print("Command execution failed.")
In this example, therun_command
function encapsulates the()
calls and handles several possible scenarios:
(1) Successful execution of the command (return code 0): Standard output is returned,None
as error output, and a return code.
(2) Command execution failure (return code non-zero): captureexception and returns
None
as standard output, error output, and return codes.
(3) Other exceptions: catch and return an error message and theNone
as the return code (although in this particular example, since the()
Usually only throwsCalledProcessError
(so this part may not be executed).
Please note.()
(used form a nominal expression)check=True
parameter is automatically thrown when the command returns a non-zero exit codeCalledProcessError
exception, which makes it possible totry-except
block to catch it. However, in this example, I chose to catch the exception explicitly to allow for more flexible handling of the output and return codes. If we only want to throw an exception if the command fails and don't care about the specifics of the error handling, then we can catch it in the call to the()
current settingcheck=True
, and let Python's default exception handling mechanism handle it.
3. shell programming and shell commands
3.1 Shell Programming
Shell programming is the process of writing scripts using Shell (also known as Command Line Interpreter or Command Line Interface) as a programming language.Shell is a special program in Unix/Linux/macOS and other Unix-like operating systems, which provides an environment for the user to interact with the operating system.A Shell script is a collection of Shell commands , these commands are written in a text file and executed through a Shell interpreter to automate tasks, batch files, manage system resources etc.
Shell scripts are cross-platform because they rely heavily on shell features and commands that are similar on most Unix-like systems. However, different shells (e.g., Bash, Zsh, Fish, etc.) may have their own features and extensions, so scripts written may need to be adapted for a particular shell.
Shell programming usually includes programming elements such as variable definitions, conditional judgments, loop control, function calls, etc. However, compared with traditional programming languages, the syntax of Shell scripts is relatively simple and flexible.
3.2 Shell Commands
Shell commands are commands entered by the user in the Shell environment to perform various operations such as file management, program execution, system administration, etc. Shell commands can be either built-in to the Shell or external programs on the system.
(1)built-in command: Commands provided by the Shell itself, which are loaded into memory at Shell startup and are therefore faster to execute. Built-in commands do not depend on other programs on the system, so they are available at system startup. Common built-in commands includecd
(change catalog),echo
(displaying information),exit
(Exit Shell), etc.
(2)external command: Also known as file system commands, these commands are system-independent programs that are usually located on the/bin
、/usr/bin
、/sbin
、/usr/sbin
and other directories. When the Shell needs to execute these commands, it looks in these directories to find the corresponding program and executes it. Common external commands includels
(List the contents of the catalog),cp
(copying files or directories),mv
(moving or renaming files or directories), etc.
Shell commands can be piped (|
), redirection (>
、<
、>>
), order substitution (command
maybe$(command)
) and other mechanisms are combined to realize more complex operations. For example.ls -l | grep '^d'
command lists the details of all directories in the current directory (ls -l
List the details.grep '^d'
Filter byd
(the line that starts with the word, i.e., directory).
Shell programming and Shell commands are indispensable tools for users of Unix/Linux/macOS and other systems in their daily work, and they can greatly improve the efficiency of users and help them automate various tasks.
3.3 How to use Shell Programming
Programming with Shell mainly involves writing Shell scripts that contain a series of Shell commands that are executed through the Shell interpreter to perform specific functions. The following are the basic steps in programming with Shell:
3.3.1 Selecting the Shell
First, we need to determine which shell to use. common shells are Bash (Bourne Again SHell, the default shell in most Linux distributions), Zsh (Z Shell, with many enhancements and better user experience), Fish (Friendly Interactive SHell, known for its user-friendliness and ease of learning), and so on. known for its user-friendliness and ease of learning), and others. Bash is a good starting point for beginners because it is widely available and well documented.
3.3.2 Writing Shell Scripts
Shell scripts are usually saved in a file named.sh
in a file with the extension. We can use any text editor to write shell scripts such asnano
、vim
、emacs
or simplyecho
and redirection.
Below is an example of a simple shell script that prints out "Hello, World!
#!/bin/bash # This is a simple example of a shell script echo "Hello, World!"
In the first line of the script, the#!/bin/bash
Known as shebang, it tells the system which interpreter this script should use to execute. In this example, it specifies Bash.
3.3.3 Saving scripts
Save our script to a file, for example。
3.3.4 Assignment of execution rights
On Linux or macOS, we need to give execution permissions to a script file to be able to run it directly. We can do this using thechmod
command to do this:
chmod +x
This command gives thefile to add execute permissions.
3.3.5 Running scripts
Now, we can run our script in one of two ways:
Directly through the path and name of the script (if the script has execute permissions):
./
Note that we need to use the./
to specify that the script is located in the current directory.
Use the Shell interpreter to execute the script (whether or not the script has execute permissions):
bash
This command will tell the Bash interpreter to execute thecommands in the script.
This article on python execution shell and get the results of the article is introduced to this, more related python execution shell and get the results of the content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!