简体   繁体   English

使用子进程在python 2.7中获取tail cmd输出

[英]Getting tail cmd output in python 2.7 using subprocess

I am trying to tail a file's content through python. 我正在尝试通过python尾部文件的内容。 The code I am using is as below 我正在使用的代码如下

#! /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

The above code throws an error as below: 上面的代码抛出如下错误:

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

I see output if I execute the tail command with the filepath directly in bash. 如果我直接在bash中使用文件路径执行tail命令,则会看到输出。

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

Why is subprocess passing an extra backtick (`) when executing the tail command? 为什么子进程在执行tail命令时传递额外的反引号(`)?

Update: 更新:

I ended up using glob to find the file as @cdarke had suggested and then passing it to the Popen cmd. 我最终使用glob按照@cdarke的建议找到了文件,然后将其传递给Popen cmd。

Bash extends the '*', Popen not. Bash扩展了“ *”,Popen则没有。

Two possibilities:. 两种可能性:
1. Do it within your script and pass a filename without '*'. 1.在脚本中执行此操作,并传递不带'*'的文件名。
2. Create a Bash script and call this from python. 2.创建一个Bash脚本,然后从python调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM