【问题标题】:Escaping strings in Python subprocess.Popen在 Python subprocess.Popen 中转义字符串
【发布时间】:2016-10-11 14:57:33
【问题描述】:

我尝试在我的 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]

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

【问题讨论】:

  • 您的意思是NF&lt;5 而不是NR&lt;5
  • @HaiVu 不,NR 是记录号。

标签: python linux awk


【解决方案1】:

像这样?

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多