Skip to main content
 首页 » 编程设计

python之尝试使用 Python 子进程进行 grep,包括引用无法找到结果

2025年05月04日18zfyouxi

我有一个文件/tmp/test.txt

this is test 
that is test 

当我运行时

[test@localhost]# grep "this is" /tmp/test.txt  
this is test 

我得到了输出。

当我尝试使用 subprocess 运行相同的命令时我没有得到输出。它还返回代码 1。

import subprocess 
p = subprocess.Popen(['grep', '"this is"', '/tmp/test.txt'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
 
print p.communicate () 
('', '') 
 
# Command exit code. 
print p.poll() 
1 

我也检查答案Python Subprocess Grep在此尝试 shell=True 但它不起作用。

我缺少在子进程中放置一些东西来获取输出,但我不知道:(。

请您参考如下方法:

您正在搜索文字模式 "this is",包括引号。将命令列表中的第二个元素更改为 'this is' 而不是 '"this is"'。

仅当 shell=True 时才需要带引号的参数,在这种情况下,shell 会解释它们并仍然将 this is 不带引号传递给 grep.