Python Subprocess.pOpen运行速度慢时内存出现

2024-04-26 18:14:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个python脚本,它使用subprocess.Popen调用命令行工具look对文件进行二进制搜索。你知道吗

例如

p = subprocess.Popen('look -b "abc" testfile.txt',executable='/bin/bash', stdout=subprocess.PIPE, stderr=STDOUT, shell=True)
out, err = p.communicate()
result = out.decode()
print(result)

这段代码的作用是调用系统命令look对名为testfile.txt的文件中的字符串abc执行二进制搜索。你知道吗

只要有这段代码就可以了。你知道吗

但是,当你的内存加载了一些大文件时,它会变得非常慢。你知道吗

例如,如果您这样做:

a = read_a_large_file() #Like GBs of data
p = subprocess.Popen('look -b "abc" testfile.txt',executable='/bin/bash', stdout=subprocess.PIPE, stderr=STDOUT, shell=True)
out, err = p.communicate()
result = out.decode()
print(result)
a[0]

子流程部分需要很长时间才能执行。在shell中运行look命令非常快,因为它对已排序的文件执行二进制搜索。你知道吗

任何帮助都将不胜感激!谢谢!你知道吗


Tags: 文件txtbashbinstdout二进制resultshell