Skip to main content
 首页 » 编程设计

python之无法在 subproces.call 中运行 ffmpeg

2025年05月04日22lovecherry

所以,我有一个简单的类,我试图将来自终端 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 

并且这个文件存在。

请您参考如下方法:

问题是

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 调用。