Table of Contents
1. Use subprocess.run() (recommended method)
2. Run commands with shell characteristics (using shell=True )
3. Real-time output command execution process (not waiting for completion)
4. Execute the command and get the return value to determine whether it is successful
5. Quickly execute and get output (suitable for simple scenarios)
Common uses examples
Home Backend Development Python Tutorial python run shell command example

python run shell command example

Jul 26, 2025 am 07:50 AM
php java programming

Use subprocess.run() to safely execute shell commands and capture output. It is recommended to pass parameters in lists to avoid injection risks; 2. When shell characteristics are required, you can set shell=True, but beware of command injection; 3. Use subprocess.Popen to realize real-time output processing; 4. Set check=True to throw exceptions when the command fails; 5. In simple scenarios, you can directly call to get output; subprocess.run() should be given priority in daily use to avoid using os.system() or deprecated modules. The above methods override the core usage of executing shell commands in Python.

python run shell command example

There are many ways to execute shell commands in Python, and the most commonly used is to use the subprocess module. Here are some practical examples showing how to run shell commands in Python.

python run shell command example

This is the recommended method in Python 3.5, which is simple, safe and powerful.

 import subprocess

# Run a simple shell command result = subprocess.run(['ls', '-l'], capture_output=True, text=True)

# Output command return code, standard output and error print("return code:", result.returncode)
print("Output:\n", result.stdout)
print("Error:\n", result.stderr)

? Note: ['ls', '-l'] is to pass parameters in a list form to avoid the risk of shell injection. If shell characteristics are required (such as wildcards, pipes), add shell=True .

python run shell command example

2. Run commands with shell characteristics (using shell=True )

 import subprocess

result = subprocess.run('echo $HOME | xargs ls', shell=True, capture_output=True, text=True)
print("Output:\n", result.stdout)

⚠️ Warning: Be careful when using shell=True to prevent command injection.


3. Real-time output command execution process (not waiting for completion)

If you want to see real-time output of commands (such as long-running scripts):

python run shell command example
 import subprocess

# Real-time printout process = subprocess.Popen(['ping', '-c', '5', 'google.com'], stdout=subprocess.PIPE, text=True)

for line in process.stdout:
    print("Output:", line.strip())

process.wait() # Wait for completion print("Complete, return code:", process.returncode)

4. Execute the command and get the return value to determine whether it is successful

 import subprocess

try:
    subprocess.run(['python', '--version'], check=True, capture_output=True, text=True)
    print("Command execution succeeded")
except subprocess.CalledProcessError as e:
    print("Command execution failed:", e)
  • check=True will throw an exception when the command returns to a non-zero state.

5. Quickly execute and get output (suitable for simple scenarios)

If you just want to get the command output quickly, you can use:

 import subprocess

# Concise writing output = subprocess.run('date', shell=True, capture_output=True, text=True).stdout.strip()
print("Current time:", output)

Common uses examples

  • Check if the file exists:

     result = subprocess.run(['test', '-f', 'config.txt'], capture_output=True)
    if result.returncode == 0:
        print("File exists")
  • Execute the Git command:

     result = subprocess.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], capture_output=True, text=True)
    print("Current branch:", result.stdout.strip())

    Basically these common methods. It is recommended to use subprocess.run() on a daily basis to avoid using deprecated os.system() or commands modules.

    The above is the detailed content of python run shell command example. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

How to convert a string from one character encoding to another in PHP How to convert a string from one character encoding to another in PHP Oct 09, 2025 am 03:45 AM

Use the mb_convert_encoding() function to convert a string between different character encodings. Make sure that PHP's MultibyteString extension is enabled. 1. The format of this function is mb_convert_encoding (string, target encoding, source encoding), such as converting ISO-8859-1 to UTF-8; 2. It can be combined with mb_detect_encoding() to detect the source encoding, but the result may be inaccurate; 3. It is often used to convert old encoding data to UTF-8 to adapt to modern applications; 4. The alternative iconv() supports the //TRANSLIT and //IGNORE options, but the cross-platform consistency is poor; 5. Recommended first

Level Devil system requirements for PC Level Devil system requirements for PC Oct 08, 2025 am 05:22 AM

TorunLevelDevilsmoothly,ensureyourPCmeetsthesystemrequirements:minimumforbasicperformance,recommendedforhighsettings,andhigh-endfor4Kwithraytracing.UseWindows10/1164-bit,adequateRAM,adedicatedGPU,andSSDforbestresults.

How to remove restrictions on copying web pages in UC Browser_How to remove restrictions on copying web pages in UC Browser How to remove restrictions on copying web pages in UC Browser_How to remove restrictions on copying web pages in UC Browser Oct 10, 2025 am 11:09 AM

1. Turn on the reading mode of UC Browser to bypass copy restrictions. Click the book icon and long press the text to copy; 2. Disable JavaScript to remove script protection. Go to settings to turn off this function and refresh the page; 3. Use the webpage snapshot function to load content in a simplified form, peel off the control script and freely select to copy; 4. Trigger text re-rendering through the translation function to invalidate the anti-copy script to complete the copy.

Fix for LOL firewall blocking game connection issue Fix for LOL firewall blocking game connection issue Oct 05, 2025 am 06:34 AM

IfLeagueofLegendscan'tconnectduetofirewallissues,trythesesteps:1.AllowLeagueClient.exethroughWindowsFirewall.2.RepairorreinstallRiotClientservices.3.Createcustominbound/outboundfirewallrules.4.Temporarilydisablethird-partyantivirusfirewallstotestconn

How to work with multidimensional arrays in java How to work with multidimensional arrays in java Oct 06, 2025 am 03:48 AM

AmultidimensionalarrayinJavaisanarrayofarrays,commonlyusedtorepresenttablesormatrices;forexample,a2Darraylikeint[][]matrix=newint[2][3];createsa2×3gridinitializedtozero.Sucharrayscanbedeclaredusingthenewkeywordorinitializerlists,includingjagged(ragge

How to use the array_reduce function in PHP How to use the array_reduce function in PHP Oct 06, 2025 am 03:45 AM

The array_reduce function simplifies an array into a single value by iteratively applying a callback function, and is often used to sum, splice strings, or convert data structures. 1. The syntax is array_reduce($array,$callback,$initial), and $callback receives $carry (cumulative value) and $item (current element). 2. Summarization example: $numbers=[1,2,3,4,5], the result after callback accumulation is 15. 3. String splicing: Use "Fruits:" as the initial value, add elements one by one, and get "Fruits:,apple,banana,cherry&qu

How to prevent Cross-Site Scripting (XSS) in PHP How to prevent Cross-Site Scripting (XSS) in PHP Oct 10, 2025 am 01:36 AM

PreventXSSinPHPbyvalidatingandsanitizinginputwithfilter_var()andavoidingHTMLunlessusinglibrarieslikeHTMLPurifier.2.Escapeoutputusinghtmlspecialchars(),json_encode(),andurlencode()basedoncontext.3.ImplementContentSecurityPolicy(CSP)headerstorestrictsc

How to get data from a GET request in PHP How to get data from a GET request in PHP Oct 07, 2025 am 03:05 AM

Use the $_GET hyperglobal array to get query parameters in the URL, such as example.php?name=John&age=30, which can be accessed through $_GET['name'] and $_GET['age']; you need to use isset() to check whether the parameters exist and provide default values ​​with ??; the input must be verified and filtered through filter_input() to ensure security.

See all articles