簡體   English   中英

Grep perl regex 在終端中有效,但在從 python 執行時無效

[英]Grep perl regex works in terminal but not when executed from python

我與 perl regex 一起使用的 Grep 命令在終端中運行良好,但是當我嘗試從 python subprocess.run/subprocess.Popen/os.system 等執行它時,它崩潰了。 我想在 python 中執行的操作:

subprocess.Popen("grep -r -n -w -Pz /(?s)somepattern\(.*\n.*\) ${PWD%/*/*/*} --include \*.py --exclude-dir={lib} > result.txt".split())

和錯誤:

grep: .*\): No such file or directory
grep: ${PWD%/*/*/*}: No such file or directory
grep: >: No such file or directory
grep: result.txt: No such file or directory

但是當我在終端中執行上述命令時:

grep -r -n -w -Pz '(?s)somepattern(.*\n.*)' ${PWD%/*/*/*} --include \*.py --exclude-dir={lib} > result.txt

這行得通。

嘗試這個:

subprocess.Popen(r"grep -r -n -w -Pz /(?s)somepattern\(.*\n.*\) ${PWD%/*/*/*} --include \*.py --exclude-dir={lib} > result.txt".split())

字符串之前的r導致 Python 將其視為“原始字符串文字”,即反斜杠不會用於轉義后續字符,而是充當普通字符本身(例如r'\\hello' == ' \\你好'`)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM