python - 我如何在 Python 中执行 comm Linux 命令

标签 python linux bash

我想从 File1 中提取 File2 中不存在的行

文件1

a  
b  
c  

文件2

a  
c  

所以输出应该是:

b  

bash 中一个可能的命令是:

comm -23 <(sort File1) <(sort File2) > File  

它在 bash 中运行得很好,但我不知道如何在 Python 中正确实现。

我试过

import os  
os.system("comm -23 <(sort File1) <(sort File2) > File")  

而且不工作。 有什么提示吗?

最佳答案

纯 Python 解决方案怎么样?

with open('file1', 'r') as f:
    lines1 = set(f.read().splitlines())

with open('file2', 'r') as f:
    lines2 = set(f.read().splitlines())

print(lines1.difference(lines2))

或者以更少的内存开销:

with open('file1') as f, open('file2') as f2:
    lines1 = set(map(str.rstrip, f))
    print(lines1.difference(map(str.rstrip, f2)))

关于python - 我如何在 Python 中执行 comm Linux 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34426283/

相关文章:

linux - virtualenv yolk 调用中的 python3 导致 IOError

我们只能重新编译内核源代码树中的内核模块吗?

mysql - 用于在 MySQL 中插入值的 Bash 脚本

git - 如何为 bash 脚本编写基于 Web 的 GUI?

c++ - 我可以在扩展 Python 的同时使用 C++ 功能吗?

python - 如何使用 PySerial 从 COM 端口读取和写入?

sql - 使用 MySQL 的 'KEY' 的重复条目 'PRIMARY'

linux - 将 bash 参数中的多个不同内容添加到名为的 sql 脚本中的变量集

python - 如何聚合这些数据并使用 python 和 pandas 创建一个新列?

python - 随机访问磁盘上保存的 numpy 数组