python - 需要帮助在 python 中调用 awk 和 sed

python - need help calling awk and sed in python

我在 bash(Linux) 上测试了以下命令,它工作正常:

awk '/string1\/parameters\/string2/' RS= myfile | grep Value | sed 's/.*"\(.*\)"[^"]*$//'

现在我必须在 python 脚本中调用它,而 string1 和 string2 是 python 变量。

我用 os.popen 试过了,但我不知道如何连接这些字符。

有解决这个问题的想法吗?

预先感谢您的帮助!

您可以使用 subprocess.check_output() 并使用 format():

将变量替换到命令中
cmd = """awk '/{}\/parameters\/{}/' RS= myfile | grep Value | sed 's/.*"\(.*\)"[^"]*$//'""".format('string1', 'string2')
cmd_output = subprocess.check_output(cmd, shell=True)

但请注意参考文档中关于使用 shell=True 的警告。

另一种方法是使用 Popen():

自行设置管道
import shlex
from subprocess import Popen, PIPE

awk_cmd = """awk '/{}\/parameters\/{}/' RS= myfile""".format('s1', 's2')
grep_cmd = 'grep Value'
sed_cmd = """sed 's/.*"\(.*\)"[^"]*$//'"""

p_awk = Popen(shlex.split(awk_cmd), stdout=PIPE)
p_grep = Popen(shlex.split(grep_cmd), stdin=p_awk.stdout, stdout=PIPE)
p_sed = Popen(shlex.split(sed_cmd), stdin=p_grep.stdout, stdout=PIPE)

for p in p_awk, p_grep:
    p.stdout.close()

stdout, stderr = p_sed.communicate()
print stdout

您可以 replace shell pipeline 使用 Popen:

from subprocess import PIPE,Popen
from shlex import split

p1 = Popen(split("awk /string1\/parameters\/string2 RS=myfile"), stdout=PIPE)
p2 = Popen(["grep", "Value"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
p3 = Popen(split("""sed 's/.*"\(.*\)"[^"]*$//'"""), stdin=p2.stdout, stdout=PIPE)
p2.stdout.close() # Allow p2 to receive a SIGPIPE if p3 exits.

output = p3.communicate()[0]