博客
关于我
Python - 如何使用管道执行shell命令,但没有‘shell = True‘?
阅读量:806 次
发布时间:2023-03-05

本文共 962 字,大约阅读时间需要 3 分钟。

在Python中,如果你想执行shell命令却不想设置shell=True,可以使用subprocess模块。通过将命令放入一个列表中,你可以实现这一点。

比如,以下代码可以执行ls -l命令:

import subprocesscommand = ['ls', '-l']with subprocess.Popen(command, stdout=subprocess.PIPE) as process:    output, error = process.communicate()print('Output:', output.decode())

这里,subprocess.Popen创建了一个新的进程,执行指定的命令。stdout=subprocess.PIPE表示将标准输出捕获到output变量中。communicate()方法会等待子进程完成,并返回输出结果。

如果你也需要捕获错误输出,可以这样做:

import subprocesscommand = ['ls', '-l']with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as process:    output, error = process.communicate()print('Output:', output.decode())if error:    print('Error:', error.decode())

此外,你可以设置环境变量:

import subprocesscommand = ['ls', '-l']env = {'PATH': '/usr/local/bin:$PATH'}with subprocess.Popen(command, stdout=subprocess.PIPE, env=env) as process:    output, error = process.communicate()print('Output:', output.decode())

记得处理输出时要注意编码问题,使用decode()方法将字节转换为字符串。如果你需要处理多个命令,可以将它们放入同一个列表中。

转载地址:http://eiafk.baihongyu.com/

你可能感兴趣的文章
python 基础第七篇
查看>>
Python编程:Tkinter图形界面设计(1)
查看>>
Python 基础语法:None
查看>>
Python 基础语法:基本数据类型(一)
查看>>
python编程读取写入excel_Python读取txt内容写入xls格式excel中的方法
查看>>
Python 基础语法:基本数据类型(字典)
查看>>
Python 基础语法:基本数据类型(字符串)
查看>>
Python 基础语法:基本数据类型(集合)
查看>>
Python编程的终极十大工具
查看>>
python 堆排序
查看>>
python编程方式之一-函数式编程
查看>>
python 复习计划
查看>>
Python 多处理 apply_async 永远不会在 Windows 7 上返回结果
查看>>
Python 多处理 Numpy 随机
查看>>
Python 多处理 >= 125 列表永远不会完成
查看>>
Python 多处理:在第一个子错误时中止映射
查看>>
Python 多处理不断产生 pythonw.exe 进程而不做任何实际工作
查看>>
Python 多处理从不加入
查看>>
Python 多处理如何优雅地退出?
查看>>
Python 多处理将子进程的标准输出重定向到 Tkinter 文本
查看>>