1

所以,我有一个简单的类,我试图将来自终端 ffmpeg 命令的字符串响应保存到对象属性中:

import os
import subprocess

class Movie(object):

    absolute_path = None
    movie_info = None

    def __init__(self, path):
        self.absolute_path = "%s/%s" % (os.getcwd(), path)
        if(os.path.exists(self.absolute_path) is False):
            raise IOError("File does not exist")

    def get_movie_info(self):
        ffmpeg_command = "ffmpeg -i %s" % self.absolute_path
        self.movie_info = subprocess.call(ffmpeg_command)
        print self.movie_info

然后当我在 cmd 中运行此命令时:

import os
import sys
sys.path.append(os.getcwd())

from Encode.Movie import Movie

try:
    movie = Movie("tests/test_1.mpg")
    movie.get_movie_info()
except IOError as e:
    print e

我得到这个例外:

richard@richard-desktop:~/projects/hello-python$ python main.py 
Traceback (most recent call last):
  File "main.py", line 9, in <module>
    movie.get_movie_info()
  File "/home/richard/projects/hello-python/Encode/Movie.py", line 16, in get_movie_info
    self.movie_info = subprocess.call(ffmpeg_command)
  File "/usr/lib/python2.7/subprocess.py", line 493, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

路径是正确的,因为当我在 subprocess.call() 之前打印 self.absolute_path 时,我得到:

/home/richard/projects/hello-python/tests/test_1.mpg

并且这个文件存在。

4

3 回答 3

6

问题是

ffmpeg_command = "ffmpeg -i %s" % self.absolute_path
self.movie_info = subprocess.call(ffmpeg_command)
  • 你给一个字符串作为命令行,但你省略了参数shell=True

但是,推荐的方法是

ffmpeg_command = ["ffmpeg", "-i", self.absolute_path]
self.movie_info = subprocess.call(ffmpeg_command)

为了分别给出命令和参数。这样,您在引用等方面没有问题,并且您省略了不必要的 shell 调用。

于 2012-06-27T12:20:54.550 回答
1

顺便说一句,如果要将命令的输出存储在变量中,则应使用check_output而不是call

http://docs.python.org/library/subprocess.html#subprocess.check_output

于 2012-06-27T12:31:26.677 回答
1

我实际上使用了这种从 ffmpeg 获取输出的方式,因为它是一个错误输出:

    ffmpeg_command = ["avconv", "-i", self.absolute_path]
    p = Popen(ffmpeg_command, stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate()
于 2012-06-27T14:23:29.760 回答