为什么使用subprocess.Popen()调用grep要比使用subprocess.check_output()快得多

问题描述 投票:0回答:1

我需要在类似csv的文件中提取条目行,我正在使用grep在python脚本中执行它。我注意到当我使用subprocess.check_output调用grep时,完成需要大约5.28秒。但是当我使用subprocess.Popen时,它只需要0.002秒。这似乎是一个巨大的差异,我想知道我应该使用哪一个。应该注意,我打算将每一行作为字符串处理。

这是我的python脚本的一部分。

myenv = os.environ.copy()
myenv['LC_ALL'] = 'C'
file = data_path+'/'+files[12]
start = time.time()
match = 'chr3' + "[[:space:]]"
matched_reads = subprocess.Popen(['grep', match, file], stdout=subprocess.PIPE, env=myenv)
mathced_reads = str(matched_reads).splitlines()
end = time.time()
runtime = end-start
print("Popen Grep: ", runtime)

start = time.time()
match = 'chr3' + "[[:space:]]"
matched_reads = subprocess.check_output(['grep', match, file],env=myenv)
mathced_reads = str(matched_reads).splitlines()
end = time.time()
runtime = end-start
print("Checkoutput Grep: ", runtime)
python time grep subprocess
1个回答
0
投票

您会发现调用Popen实际上并不执行程序并返回输出,而是构造一个引用创建过程的对象。在你的情况下,你没有调用Popen.communicate,它与进程“对话”并捕获其输出完成。而check_output为你做了所有这些。你会发现communicate方法需要花费很长时间,但实际上会返回所需的输出。

对于POpen的实际演示,请替换

matched_reads = subprocess.Popen(['grep', match, file], stdout=subprocess.PIPE, env=myenv)

process = subprocess.Popen(['grep', match, file], stdout=subprocess.PIPE, env=myenv)
matched_reads, stderr = process.communicate()

哪个应该复制与check_output相同的行为,让matched_reads包含grep产生的输出。

© www.soinside.com 2019 - 2024. All rights reserved.