使用subprocess.run()执行命令并捕获输出,推荐列表传参以避免注入风险;os.system()仅执行命令无输出捕获,os.popen()可读输出但已过时;错误处理可通过检查returncode、捕获stderr或使用try-except捕获CalledProcessError;后台执行用subprocess.Popen()并调用wait()等待结束;实时输出需结合Popen与TextIOWrapper逐行读取。

Python执行系统命令,本质上就是让Python程序能够调用操作系统提供的功能。方法有很多,关键在于选择最适合你需求的。
直接输出解决方案即可: Python提供了多种方法来执行系统命令,常见的有
os.system()
os.popen()
subprocess
subprocess
subprocess
run()
ls -l
import subprocess result = subprocess.run(['ls', '-l'], capture_output=True, text=True, check=True) print(result.stdout)
这段代码中,
capture_output=True
text=True
check=True
check=False
result.returncode
subprocess.run()
立即学习“Python免费学习笔记(深入)”;
os.system()
os.popen()
os.system()
import os
os.system('ls -l')os.popen()
import os
output = os.popen('ls -l').read()
print(output)通常情况下,
subprocess
os.system()
os.popen()
执行系统命令时,可能会遇到各种错误,例如命令不存在、权限不足、参数错误等。使用
subprocess
检查返回码:
subprocess.run()
result
returncode
returncode
捕获标准错误:
subprocess.run()
capture_output=True
result.stderr
Shell本身是一个用C语言编写的程序,它是用户使用Linux的桥梁。Shell既是一种命令语言,又是一种程序设计语言。作为命令语言,它交互式地解释和执行用户输入的命令;作为程序设计语言,它定义了各种变量和参数,并提供了许多在高级语言中才具有的控制结构,包括循环和分支。它虽然不是Linux系统核心的一部分,但它调用了系统核心的大部分功能来执行程序、建立文件并以并行的方式协调各个程序的运行。因此,对于用户来说,shell是最重要的实用程序,深入了解和熟练掌握shell的特性极其使用方法,是用好Linux系统
24
使用try...except
try...except
subprocess.CalledProcessError
check=True
import subprocess
try:
result = subprocess.run(['ls', '-z'], capture_output=True, text=True, check=True)
print(result.stdout)
except subprocess.CalledProcessError as e:
print(f"命令执行失败:{e}")
print(f"错误信息:{e.stderr}")这段代码尝试执行一个不存在的命令
ls -z
check=True
subprocess.CalledProcessError
except
直接拼接字符串来构建命令是很危险的,因为它容易受到shell注入攻击。应该使用列表来传递命令及其参数,这样
subprocess
例如,假设要执行
grep
import subprocess search_string = 'hello world' result = subprocess.run(['grep', search_string, 'file.txt'], capture_output=True, text=True) print(result.stdout)
如果直接使用字符串拼接,可能会出现问题,特别是当
search_string
要在后台执行系统命令,可以使用
subprocess.Popen()
import subprocess
process = subprocess.Popen(['sleep', '10']) # 在后台执行sleep 10命令
# 可以执行其他操作,不会被sleep命令阻塞
print("命令已在后台执行")
process.wait() # 等待后台进程结束
print("命令执行完毕")subprocess.Popen()
Popen
wait()
wait()
有时候,需要实时显示系统命令的执行结果,而不是等到命令执行完毕后再输出。可以使用
subprocess.Popen()
io.TextIOWrapper
import subprocess
import io
process = subprocess.Popen(['ping', 'www.google.com'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout_reader = io.TextIOWrapper(process.stdout, encoding='utf-8')
stderr_reader = io.TextIOWrapper(process.stderr, encoding='utf-8')
while True:
stdout_line = stdout_reader.readline()
stderr_line = stderr_reader.readline()
if stdout_line:
print(stdout_line.strip())
if stderr_line:
print(stderr_line.strip())
if process.poll() is not None:
break
process.wait()这段代码使用
subprocess.Popen()
ping www.google.com
io.TextIOWrapper
process.poll()
以上就是Python怎么执行系统命令_Python调用系统命令方法详解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号