8

I am creating a program using python by importing moviepy library, but getting following error:

from moviepy.editor import VideoFileClip

white_output = 'videos/testVideo.mp4'
clip1 = VideoFileClip("videos/testVideo.mp4")

OSError                                   Traceback (most recent call last)
<ipython-input-40-f49638833528> in <module>()
      1 white_output = 'videos/testVideo.mp4'
----> 2 clip1 = VideoFileClip("videos/testVideo.mp4")
      3 white_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!
      4 get_ipython().magic('time white_clip.write_videofile(white_output, audio=False)')

C:\Users\hp pc\Anaconda3\envs\lib\site-packages\moviepy\video\io\VideoFileClip.py in __init__(self, filename, has_mask, audio, audio_buffersize, audio_fps, audio_nbytes, verbose)
     53         # Make a reader
     54         pix_fmt= "rgba" if has_mask else "rgb24"
---> 55         reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt)
     56         self.reader = reader
     57         # Make some of the reader's attributes accessible from the clip

C:\Users\hp pc\Anaconda3\envs\lib\site-packages\moviepy\video\io\ffmpeg_reader.py in __init__(self, filename, print_infos, bufsize, pix_fmt, check_duration)
     30 
     31         self.filename = filename
---> 32         infos = ffmpeg_parse_infos(filename, print_infos, check_duration)
     33         self.fps = infos['video_fps']
     34         self.size = infos['video_size']

C:\Users\hp pc\Anaconda3\envs\lib\site-packages\moviepy\video\io\ffmpeg_reader.py in ffmpeg_parse_infos(filename, print_infos, check_duration)
    236         popen_params["creationflags"] = 0x08000000
    237 
--> 238     proc = sp.Popen(cmd, **popen_params)
    239 
    240     proc.stdout.readline()

C:\Users\hp pc\Anaconda3\envs\lib\subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds)
    840                  pass_fds=()):
    841         """Create new Popen instance."""
--> 842         _cleanup()
    843         # Held while anything is calling waitpid before returncode has been
    844         # updated to prevent clobbering returncode if wait() or poll() are

C:\Users\hp pc\Anaconda3\envs\lib\subprocess.py in _cleanup()
    503 def _cleanup():
    504     for inst in _active[:]:
--> 505         res = inst._internal_poll(_deadstate=sys.maxsize)
    506         if res is not None:
    507             try:

C:\Users\hp pc\Anaconda3\envs\lib\subprocess.py in _internal_poll(self, _deadstate, _WaitForSingleObject, _WAIT_OBJECT_0, _GetExitCodeProcess)
   1257             """
   1258             if self.returncode is None:
-> 1259                 if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
   1260                     self.returncode = _GetExitCodeProcess(self._handle)
   1261             return self.returncode

OSError: [WinError 6] The handle is invalid

Please let me know a workaround.

Deepak Tekchandani
  • 488
  • 2
  • 5
  • 15
  • 1
    It's difficult to say without additional context. When `Popen` is called it does some internal cleanup via the `_cleanup` function, which checks to see if any deleted `Popen` instances are still running and tries to wait on them and get the exit status. This is really only required on Unix systems to avoid zombies. On Windows it suffices to let the `Popen` instance get collected which in turn collects the `Handle` instance for the process handle, which calls `CloseHandle`, and that's it. If the handle is invalid, that's weird and shouldn't happen, but it's an error we could ignore on Windows. – Eryk Sun May 14 '17 at 17:47
  • 1
    As a workaround, you could monkeypatch `subprocess._cleanup()` to ignore the error. Or you could investigate deeper to find out what's closing the `_handle` of the deleted `Popen` instance. That's going to require using a native debugger. – Eryk Sun May 14 '17 at 17:50
  • @eryksun: Thanks for the suggestion. I am novice python programmer, will surely try your proposition. Since the use of this function is a necessity, could you help me to execute it successfully? – Deepak Tekchandani May 15 '17 at 03:14
  • 1
    I dont know if this helps, but I was getting this error because I had a windows explorer window open, and maybe the system was generating tumbnails or something. once I closed the window everything worked fine – gene tsai Nov 17 '17 at 09:23

4 Answers4

27

I solved the issue by running the following commands after reading the video.

video_clip.reader.close()
video_clip.audio.reader.close_proc()

See https://github.com/Zulko/moviepy/issues/73 and https://github.com/Zulko/moviepy/issues/164.

Diomidis Spinellis
  • 18,734
  • 5
  • 61
  • 83
6

Somehow python.exe was failing and because of that internal function like VideoFileClip was giving error in jupyter-notebook.

Then I closed everything and restarted back and voila, error was gone and it's working fine now.

Deepak Tekchandani
  • 488
  • 2
  • 5
  • 15
  • I assumed you would have tried restarting and that something was reliably causing a bad process handle every time, which would never get removed because `_cleanup` would fail repeatedly. – Eryk Sun May 15 '17 at 13:25
  • Chances are you do have a bug somewhere in the software stack (not necessarily in your own code) that caused some routine to close the process handle. It need not have anything to do subprocess. For example, some code may have had a file handle that got closed out from under it. Then the handle number was reused as a process handle, which in turn the original file-handle owner unknowingly closed, expecting that it was closing the file. It can be difficult to diagnose a problem like this without a debugger. – Eryk Sun May 15 '17 at 13:28
  • @eryksun: Actually one dialog box came and asked for debugging and there indeed it was failing for quite a few times. And I saw the same behaviour many times today and every time I had to restart jupyter-notebook. So what do you think shall I mark out this as an answer, or would you like to provide an insightful one? – Deepak Tekchandani May 15 '17 at 18:33
  • I cannot give a more insightful answer. This kind of issue is a poor match for Stack Overflow. The only generic answer I have is to monkeypatch `subprocess._cleanup`, and I don't particularly like that option. – Eryk Sun May 15 '17 at 19:04
  • @DeepakTekchandani Thanks for posting the answer. I wasted a lot of time. Restart! – SeanJ Sep 27 '17 at 22:09
1

On windows 10, I did not able to call VideoFileClip() more than 5 times. clip.close() solved my issue, you need to close clips after you don't need:

clip = VideoFileClip("asd.mp4")
...
clip.close()
DaWe
  • 1,422
  • 16
  • 26
0

What worked for me, was closing Explorer, as gene tsai suggested. Worked instantly. I was using os.listdir(dirpath) when I got the error.

Si1veR
  • 67
  • 1
  • 6