在Python subprocess.Popen

时间:2016-06-10 15:11:32

标签: python linux awk

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

但它似乎没有正确地逃避文字。

1 个答案:

答案 0 :(得分:0)

像这样?

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

OR

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)