在Python中使用run()函数并返回命令行输出结果的方法
发布时间:2024-01-02 04:03:30
在Python中,可以使用subprocess模块中的run()函数来运行命令行命令,并返回命令行输出结果。下面是使用run()函数的一些示例。
首先,需要导入subprocess模块:
import subprocess
1. 执行简单的命令并返回输出结果:
# 执行命令 result = subprocess.run(['ls'], capture_output=True, text=True) # 获取输出结果,并打印 output = result.stdout print(output)
2. 执行命令时传递参数:
# 执行带参数的命令 result = subprocess.run(['ls', '-l', '/tmp'], capture_output=True, text=True) # 获取输出结果,并打印 output = result.stdout print(output)
3. 检查命令的执行状态:
# 执行命令
result = subprocess.run(['ls', '-l', '/non/existent/path'], capture_output=True, text=True)
# 检查命令的执行状态
if result.returncode == 0:
print("Command executed successfully")
else:
print(f"Command execution failed with return code {result.returncode}")
# 获取输出结果,并打印
output = result.stdout
print(output)
4. 捕获命令的错误信息:
# 执行命令
result = subprocess.run(['ls', '-l', '/non/existent/path'], capture_output=True, text=True)
# 检查命令的执行状态
if result.returncode == 0:
print("Command executed successfully")
else:
# 获取错误信息,并打印
error_message = result.stderr
print(f"Command execution failed with error: {error_message}")
# 获取输出结果,并打印
output = result.stdout
print(output)
5. 忽略命令的输出结果:
# 执行命令,忽略输出结果 subprocess.run(['ls', '-l', '/tmp'])
在使用run()函数时,我们可以通过capture_output=True参数来捕获命令的输出结果,通过text=True参数将输出结果转换为字符串。此外,还可以使用stdout=subprocess.PIPE和stderr=subprocess.PIPE参数来分别捕获标准输出和错误输出。
需要注意的是,在使用run()函数时,默认情况下,命令是在子进程中执行的,可以通过shell=True参数来在当前进程中执行命令。
总的来说,使用subprocess模块中的run()函数可以方便地在Python中执行命令行命令,并获取命令的输出结果。
