python - 使用列表参数的子进程中的Python内部管道?
问题描述
可以创建这样的子流程...
commandlist = ['cat', '/some/file']
sp = subprocess.Popen(commandlist)
但是是否可以将该序列的输出通过管道传输到同一子进程内的另一个命令中?
例如,序列/列表等价于cat /some/file | sed 's/foo/bar/'
什么?
我想避免使用字符串输入,shell=True
并且想知道是否可以在不创建 2 个子进程的情况下完成。
谢谢,克里斯
解决方案
管道语法是一个 shell 结构,所以你可以使用 shell 来执行它:
sp = subprocess.Popen("cat /some/file | sed 's/foo/bar/'", shell=True)
但管道本身并不局限于外壳,因此您可以在 Python 中建立管道:
sp1 = subprocess.Popen(['cat', '/some/file'], stdout=subprocess.PIPE)
sp2 = subprocess.Popen(['sed', 's/foo/bar'], stdin=sp1.stdout)
推荐阅读
- entity-framework - MassTransit 实体框架审计存储 SentTime 不可用
- javascript - 在 NgRx (Angular) 的效果中将动作链接在一起
- c - 输入大小写时,切换案例菜单不退出程序
- python - 通过比较同一数据框中的两列来更新列
- roc - roc_curve 指标中的阈值大于 1 是否可以?
- python - IB_insync 为共享返回小整数(1 = 100, 0 = 50?)需要浮点数或适当缩放的整数
- shell - 如何将包含特定数字的目录中的文件移动到不同的目录中?
- python - pip 安装频谱,没有额外内容
- python - 对没有返回值的方法进行单元测试
- javascript - 当死代码引用不存在的模块时使用 webpack 构建失败 - 这是不可避免/预期的行为吗?