【问题标题】:Getting tail cmd output in python 2.7 using subprocess使用子进程在python 2.7中获取tail cmd输出
【发布时间】:2017-08-01 03:55:51
【问题描述】:

我正在尝试通过 python 跟踪文件的内容。我使用的代码如下

#! /usr/bin/python

import subprocess
import os.path

# Get the file path
filepath = os.path.join(baseDir,"filename.*" + uniqueId)
# Call subprocess and get last 10 lines from file
spTailFile = subprocess.Popen(["tail", "-10", filepath ], stdout=subprocess.PIPE)
tailOutput = spTailFile.communicate()[0]
print tailOutput

以上代码抛出如下错误:

tail: cannot open `/hostname/user/app/filename.*39102'

如果我直接在 bash 中使用文件路径执行 tail 命令,我会看到输出。

tail -10 /hostname/user/app/filename.*39102

为什么子进程在执行tail命令时会传递一个额外的反引号(`)?

更新:

我最终按照@cdarke 的建议使用 glob 查找文件,然后将其传递给 Popen cmd。

【问题讨论】:

  • 另一种可能性:使用 Python 函数 glob.glob("filename.*") 获取文件名列表。另一种可能性:将shell=True 添加到您的Popen 参数中,因为它是执行文件名扩展(通配符)的shell。

标签: python linux bash python-2.7 subprocess


【解决方案1】:

Bash 扩展了 '*',Popen 没有。

两种可能性:.
1. 在您的脚本中执行此操作并传递不带“*”的文件名。
2. 创建一个 Bash 脚本并从 python 调用它。

【讨论】:

  • 你是对的,Bash 正在扩展导致尾部问题的“*”。传入完整文件名后,cmd按预期执行。
猜你喜欢
  • 2018-02-04
  • 2016-08-11
  • 2011-09-08
  • 2015-12-07
  • 2017-11-24
  • 2022-06-19
  • 2013-08-18
  • 2013-05-12
  • 2020-03-03
相关资源
最近更新 更多