2014-03-31 37 views
1

我目前正在使用:如何使用pymongo從mongodb獲取文件對象?

some_fs = gridfs.GridFS(db, "some.col") 
fs_file = some_fs.get(index) 

獲得<class 'gridfs.grid_file.GridOut'>對象。

我該如何獲取文件對象,或者如何將其轉換爲python文件對象? 我必須保存爲臨時文件才能做到這一點嗎?

編輯:

這是完整的代碼我使用:

FFMPEG_BIN = "ffmpeg.exe" 
some_fs = gridfs.GridFS(db, "some.col") 
vid_id = ObjectId("5339e3b5b322631b544b2338") 

vid_file = some_fs.get(vid_id) 
raw = vid_file.read() 
print type(vid_file), type(raw) 

with open(raw, "rb") as infile: 
    pipe = sp.Popen([FFMPEG_BIN, 
       # "-v", "quiet", 
       "-y", 
       "-i", "-", 
       "-vcodec", "copy", "-acodec", "copy", 
       "-ss", "00:00:00", "-t", "00:00:10", "-sn", 
       "test.mp4" ] 
       ,stdin=infile, stdout=sp.PIPE 
) 
pipe.wait() 

輸出:

[2014-03-31 19:03:00] Connected to DB. 
<class 'gridfs.grid_file.GridOut'> <type 'str'> 
Traceback (most recent call last): 
    File "C:/dev/proj/src/lib/ffmpeg/win/test.py", line 19, in <module> 
    with open(raw, "rb") as infile: 
TypeError: file() argument 1 must be encoded string without NULL bytes, not str 

回答

0

編輯:也許GridOut是不正確的執行python file objects。我最後的建議是嘗試使用StringIO的內存文件。

import StringIO 

FFMPEG_BIN = "ffmpeg.exe" 
some_fs = gridfs.GridFS(db, "some.col") 
vid_id = ObjectId("5339e3b5b322631b544b2338") 

vid_file = some_fs.get(vid_id) 

# Should be a proper file-like object 
infile = StringIO.StringIO(vid_file.read()) 

pipe = sp.Popen([FFMPEG_BIN, 
    # "-v", "quiet", 
    "-y", 
    "-i", "-", 
    "-vcodec", "copy", "-acodec", "copy", 
    "-ss", "00:00:00", "-t", "00:00:10", "-sn", 
    "test.mp4" ] 
    ,stdin=infile, stdout=sp.PIPE 
) 
pipe.wait() 

... 

infile.close() 
+0

infile沒有設置任何東西...我應該使用什麼作爲輸入? – Jeff

+0

我編輯了我的答案來修復我的複製粘貼錯誤。 –

+0

這給了我:'TypeError:必須可轉換爲緩衝區,而不是GridOut' – Jeff

0

基於this documentation你需要使用.read()方法。

我認爲some_fs.get(index).read()會給你你所需要的。

+0

我試過......這給了我只是一個字符串。 – Jeff

+0

@Jeff你能告訴我,你有什麼樣的字符串,你期望在文件中有什麼?聽起來好像你的''實際上是一個文件對象,而read()給你的是文件內部的東西。 –

+0

我編輯了我的問題......我希望這不會改變我的問題太多! – Jeff

0

This worked for me

FFMPEG_BIN = "ffmpeg.exe" 
some_fs = gridfs.GridFS(db, "some.col") 
vid_id = ObjectId("5339e3b5b322631b544b2338") 

vid_file = some_fs.get(vid_id) 

pipe = sp.Popen([FFMPEG_BIN, 
    # "-v", "quiet", 
    "-y", 
    "-i", "-", 
    "-vcodec", "copy", "-acodec", "copy", 
    "-ss", "00:00:00", "-t", "00:00:10", "-sn", 
    "test.mp4" ] 
    ,stdin=sp.PIPE, stdout=sp.PIPE 
) 
pipe.stdin=vid_file.read()