Python子进程中的Awk给出了无效表达式“'”

2024-04-26 03:09:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图读取文件名和文件戳,以获取代码中两个命名方案中每一个的最新文件名。我大致有以下代码:

#!/usr/bin/env python
import string, subprocess, sys, os
mypath = "/path/to/file"


my_cmd = (["ls -lt --full-time " + mypath + "*DAI*.txt",
          "ls -lt --full-time " + mypath + "*CA*.txt"]
         )
getmostrecent_cmd = "head -n 1"
getcols_cmd = "awk '{ print $6, $7, $9 }'"

for cmd in my_cmd:
    p1 = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
    p2 = subprocess.Popen(getmostrecent_cmd.split(), stdin=p1.stdout, stdout=subprocess.PIPE)
    p3 = subprocess.Popen(getcols_cmd.split(), stdin=p2.stdout, stdout=subprocess.PIPE)
    output = p3.communicate()[0]

    print output

会出现以下错误:

^{pr2}$

但是:

  1. 我可以使用“ls-lt--full-time/path/to/file/*DAI*.txt”并在终端中获得结果。为什么它会导致相同路径的问题?在
  2. awk命令,当直接放入子进程时,工作正常;例如子流程.Popen([“awk”,…..),stdin=..,stdout=..)工作正常。但现在我对单引号有问题。我试着用三重引号引字符串,然后转义单引号。在

Tags: lttxtcmdtime文件名stdinstdoutls
1条回答
网友
1楼 · 发布于 2024-04-26 03:09:15

I can use "ls -lt full-time /path/to/file/DAI.txt" and get a result in the terminal. Why is it causing an issue with the same path?

全局扩展由shell执行。默认情况下,shell不参与通过Popen()启动新的子进程。为此,您必须将shell=True参数传递给它:

p1 = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, shell=True)
#                                                          ^^^^^^^^^^

The awk command, when put in to subprocess directly, works fine; E.g. subprocess.Popen(["awk", ....], stdin=...., stdout=....) worked okay. But now I am getting an issue with the single quote. I tried triple quoting the string and escaping the single-quote.

在shell命令行中,awk '{ print $6, $7, $9 }'中的单引号将字符串{ print $6, $7, $9 }视为单个参数(以及防止变量扩展)。单引号被shell删除,awk只看到字符串{ print $6, $7, $9 }。由于Popen()默认情况下在执行子进程命令时不涉及shell,并将参数逐字传递给命令,因此不需要单引号:

^{pr2}$

相关问题 更多 >