【发布时间】: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