所以,我有一个简单的类,我试图将字符串响应从终端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
此文件存在。
答案 0 :(得分:4)
问题是
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调用。
答案 1 :(得分:1)
BTW,如果要将命令的输出存储在变量中,则应使用check_output
而不是call
http://docs.python.org/library/subprocess.html#subprocess.check_output
答案 2 :(得分:1)
我实际上使用这种方式从ffmpeg获取输出,因为它是一个错误输出:
ffmpeg_command = ["avconv", "-i", self.absolute_path]
p = Popen(ffmpeg_command, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()