簡體   English   中英

帶有awk和管道的Python子進程

[英]Python subprocess with awk and pipes

我的Python腳本中有以下語句:

year = '1966'
file = 'test.txt'
cmd = "awk '{FS="|"}{if ($2 == %s) print $1}' %s | sort -n | uniq | wc" % (year, file)
bla = run_command(cmd)

其中fun_command()是函數:

def run_command(command):                                     
  process = subprocess.Popen([sys.executable, command], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  retcode = process.wait()
  if retcode != 0:
    raise Exception, "Problem running command: " + command
  stdout, stderr = process.communicate()
  return stdout

產生以下輸出:

TypeError: unsupported operand type(s) for |: 'str' and 'str'

任何想法有什么問題嗎?

"awk '{FS="|"}{if ($2 == %s) print $1}' %s | sort -n | uniq | wc"
在這里,您需要轉義內部的"|"

"awk '{FS=\\"|\\"}{if ($2 == %s) print $1}' %s | sort -n | uniq | wc"

sys.executable是當前正在運行的Python解釋器,因此您嘗試將shell代碼作為Python代碼執行。 只需使用

def run_command(command):                                     
  process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  retcode = process.wait()
  if retcode != 0:
    raise Exception, "Problem running command: " + command
  stdout, stderr = process.communicate()
  return stdout

暫無
暫無

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

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