gpt4 book ai didi

python - 在 Python subprocess.Popen 中转义字符串

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:24:23 28 4
gpt4 key购买 nike

我尝试在我的 python 脚本中调用 awk 脚本。我使用 subprocess.Popen():

awk -F"\t" 'NR<5{ print "SET", "\""$1"\"", "\""$2"|"$3"|"$4"\"" }' folder/file.tsv

这是脚本:

import os
import subprocess

goal_dir = os.path.join(os.getcwd(), "folder", "file.tsv")

args = ["awk", '-F"\t"', 'NR<5{ print "SET", "\""$1"\"", "\""$2"|"$3"|"$4"\"" }', "{0}".format(goal_dir)]

process = subprocess.Popen(args, stdout=subprocess.PIPE)
output = process.communicate()[0]

但它似乎没有正确转义文字。

最佳答案

像这样吗?

subprocess.Popen(r'''awk -F"\t" 'NR<5{ print "SET", "\""$1"\"","\""$2"|"$3"|"$4"\"" }' %s''' % goal_dir, shell=True, stdout=subprocess.PIPE)

args = ["awk", '-F"\t"', r"""'NR<5{ print "SET", "\""$1"\"", "\""$2"|"$3"|"$4"\"" }'""", "{0}".format(goal_dir)]    
process = subprocess.Popen(" ".join(args), shell=True, stdout=subprocess.PIPE)

关于python - 在 Python subprocess.Popen 中转义字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37751656/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com