Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用os.system()对两个字符串进行grep_Python_Grep - Fatal编程技术网

Python 如何使用os.system()对两个字符串进行grep

Python 如何使用os.system()对两个字符串进行grep,python,grep,Python,Grep,如何使用os.system()对两个字符串进行grep 以下命令失败: os.system("grep " + "Section\|Function" + Text_file + "> results.csv") 这是可行的选择之一@玛塔给了你一张很好的清单,上面列出了更多的可能性 os.system("grep -E 'Section|Function' " + Text_file + "> results.csv") 因此,您当然需要在“函数”后面加一个空格。 此外,要

如何使用
os.system()
对两个字符串进行grep

以下命令失败:

os.system("grep " + "Section\|Function"   + Text_file +  "> results.csv")

这是可行的选择之一@玛塔给了你一张很好的清单,上面列出了更多的可能性

os.system("grep -E 'Section|Function' " + Text_file + "> results.csv")
因此,您当然需要在“函数”后面加一个空格。

此外,要搜索多个字符串,一个选项是
-E
标志,它允许在搜索条件中使用扩展正则表达式。

我认为如果使用python的字符串格式而不是
+
,搜索字符串会更容易:

os.system("grep -E 'Section|Function' {} > results.csv".format(Text_file))
-E
启用扩展正则表达式。这消除了
grep
查看转义垂直条的需要


当您运行此命令时,它将经历三个阶段:python、bash和grep。命令字符串的设计必须考虑所有三个阶段。请注意,python字符串用双引号括起来。在python中,双引号和单引号在含义上没有区别。在
bash
中,有一个重要的区别。因为python字符串用双引号括起来,所以我们可以在其中的正则表达式周围加上单引号。当
bash
看到单引号时,它将只保留正则表达式。这样,我们在python中看到的正则表达式将与传递给
grep
的正则表达式相同。模式中的反斜杠只会阻止shell解释管道符号,
grep
在本例中,请参见
Section | Function
<默认模式下的code>grep不会将管道解释为
,而是将管道解释为文字管道,仅在扩展模式下(使用
-E
标志)将其解释为
,在默认模式下,您需要使用另一个反斜杠将其转义

当字符串中有转义字符(backsalsh)并且在第二个模式后缺少空格时,应该使用原始字符串

因此,您有几个选项,这些选项都会产生相同的结果:

os.system(r"grep Section\\\|Function "   + Text_file +  "> results.csv")
os.system(r"grep 'Section\|Function' "   + Text_file +  "> results.csv")
os.system(r"grep -E Section\|Function "   + Text_file +  "> results.csv")
os.system(r"grep -E 'Section|Function' "   + Text_file +  "> results.csv")
os.system(r"grep  -e Section -e Function "   + Text_file +  "> results.csv")

输出中没有错误,但结果也没有打印出来。当我单独运行grep命令时,它工作正常,但不显示输出。输出为空。有更好的方法可以直接在Python中实现这一点。为什么不直接编写Python呢?