从 Python 调用的 grep 搜索字符串中的斜杠
Slashes in grep search string called from Python
我有以下输入文件"testFile.txt":
$ cat testFile.txt
111 // mNx
222 // mNy not nMx
333 // mNz also not nMx
我想获取 mNx 的值,但其他一些行包含有关 mNx 的注释。在 Unix 命令行上使用 grep 找到正确的行:
$ grep mNx testFile.txt
111 // mNx
222 // mNy not mNx
333 // mNz also not mNx
然而,
$ grep "// mNx" testFile.txt
111 // mNx
好的,到目前为止一切顺利,但我想使用 Python 调用 grep。从 开始,我有
from subprocess import Popen, PIPE
def grep1(inFile, string):
COMMAND = 'grep %s %s' % (string, inFile)
process = Popen(COMMAND, shell=True, stderr=PIPE, stdout=PIPE)
output, errors = process.communicate()
return output
mNx = grep1('testFile.txt', 'mNx')
print mNx
这给出了
111 // mNx
222 // mNy not mNx
333 // mNz also not mNx
现在如果我改为使用
mNx = grep1('testFile.txt', '// mNx')
它 returns 以下内容:
testFile.txt:111 // mNx
testFile.txt:222 // mNy not mNx
testFile.txt:333 // mNz also not mNx
我已尝试 "\/\/ mNx"
、r"// mNx"
、r"\/\/ mNx"
等,但无法重现本机 grep
行为。我的 Python 字符串中有什么东西被转义了吗?到底是怎么回事?
将函数调用更改为 mNx = grep1('testFile.txt', '"// mNx"')
。
问题是,我们需要命令是这样的 Python 字符串文字 'grep "// mNx" testFile.txt'
只有\
才需要转义。 /
可以表示为 Python.
我有以下输入文件"testFile.txt":
$ cat testFile.txt
111 // mNx
222 // mNy not nMx
333 // mNz also not nMx
我想获取 mNx 的值,但其他一些行包含有关 mNx 的注释。在 Unix 命令行上使用 grep 找到正确的行:
$ grep mNx testFile.txt
111 // mNx
222 // mNy not mNx
333 // mNz also not mNx
然而,
$ grep "// mNx" testFile.txt
111 // mNx
好的,到目前为止一切顺利,但我想使用 Python 调用 grep。从
from subprocess import Popen, PIPE
def grep1(inFile, string):
COMMAND = 'grep %s %s' % (string, inFile)
process = Popen(COMMAND, shell=True, stderr=PIPE, stdout=PIPE)
output, errors = process.communicate()
return output
mNx = grep1('testFile.txt', 'mNx')
print mNx
这给出了
111 // mNx
222 // mNy not mNx
333 // mNz also not mNx
现在如果我改为使用
mNx = grep1('testFile.txt', '// mNx')
它 returns 以下内容:
testFile.txt:111 // mNx
testFile.txt:222 // mNy not mNx
testFile.txt:333 // mNz also not mNx
我已尝试 "\/\/ mNx"
、r"// mNx"
、r"\/\/ mNx"
等,但无法重现本机 grep
行为。我的 Python 字符串中有什么东西被转义了吗?到底是怎么回事?
将函数调用更改为 mNx = grep1('testFile.txt', '"// mNx"')
。
问题是,我们需要命令是这样的 Python 字符串文字 'grep "// mNx" testFile.txt'
只有\
才需要转义。 /
可以表示为 Python.