我一直在尝试从Python脚本中运行此ffmpeg
命令,以从静态图像生成特定长度的视频,但我不断收到“没有这样的文件或目录”错误!下面是我的代码:
import subprocess
def generate_white_vid (duration):
ffmpeg_create_vid_from_static_img = 'ffmpeg -loop 1 -i /same_path/WhiteBackground.jpg -c:v libx264 -t %f -pix_fmt yuv420p -vf scale=1920:1080 /same_path/white_vid2.mp4' % duration
print ffmpeg_create_vid_from_static_img
pp = subprocess.Popen(ffmpeg_create_vid_from_static_img)
pp.communicate()
generate_white_vid(0.5)
然而,当我在终端中运行完全相同的命令:
ffmpeg -loop 1 -i /same_path/WhiteBackground.jpg -t 0.500000 -pix_fmt yuv420p -vf scale=1920:1080 /same_path/white_vid2.mp4
它可以正常工作。我错在哪里了?以下是完整的跟踪信息:
Traceback (most recent call last):
File "gen.py", line 10, in <module>
generate_white_vid(0.5)
File "gen.py", line 7, in generate_white_vid
pp = subprocess.Popen(ffmpeg_create_vid_from_static_img)
File "/home/ubuntu/anaconda2/lib/python2.7/subprocess.py", line 390, in __init__
errread, errwrite)
File "/home/ubuntu/anaconda2/lib/python2.7/subprocess.py", line 1024, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
当我使用列表传递ffmpeg
命令参数,如下所示:ffmpeg_create_vid_from_static_img = ['ffmpeg', '-loop', '1', '-i', '/same_path/WhiteBackground.jpg', '-c:v', 'libx264', '-t', duration, '-pix_fmt', 'yuv420p', '-vf', 'scale=1920:1080', '/same_path/white_vid.mp4']
时,我会收到类型错误:
TypeError Traceback (most recent call last)
<ipython-input-137-4a9e12e42310> in <module>()
----> 1 generate_white_vid(0.5)
<ipython-input-136-edfbfc017557> in generate_white_vid(duration)
3 ffmpeg_create_vid_from_static_img = ['ffmpeg', '-loop', '1', '-i', '/home/ubuntu/matar/multispectral/WhiteBackground.jpg', '-c:v', 'libx264', '-t', duration, '-pix_fmt yuv420p', '-vf', 'scale=1920:1080', '/home/ubuntu/matar/multispectral/white_vid.mp4']
4 print ffmpeg_create_vid_from_static_img
----> 5 pp = subprocess.Popen(ffmpeg_create_vid_from_static_img)
6 pp.communicate()
/home/ubuntu/anaconda2/lib/python2.7/subprocess.pyc in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags)
388 p2cread, p2cwrite,
389 c2pread, c2pwrite,
--> 390 errread, errwrite)
391 except Exception:
392 # Preserve original exception in case os.close raises.
/home/ubuntu/anaconda2/lib/python2.7/subprocess.pyc in _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, to_close, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
1022 raise
1023 child_exception = pickle.loads(data)
-> 1024 raise child_exception
1025
1026
TypeError: execv() arg 2 must contain only strings
Popen
中缺少参数shell=True
? - etopylightshell=False
是Popen
的默認值,通常你需要構造命令行為一個獨立的元素列表(這也更加安全)。但是,如果你只想把你的命令作為一個字符串傳遞,那麼就需要強制設置shell=True
。 - etopylight